1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::UserConfig;
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92 assert_eq!(msg_events.len(), 1);
93 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96 &ErrorAction::SendErrorMessage { .. } => {
97 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99 _ => panic!("unexpected event!"),
101 } else { assert!(false); }
104 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106 // Test all mutations that would make the channel open message insane
107 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_funding_exceeds_no_wumbo_limit() {
127 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130 let chanmon_cfgs = create_chanmon_cfgs(2);
131 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180 let mut sender_node_per_peer_lock;
181 let mut sender_node_peer_state_lock;
182 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183 chan.holder_selected_channel_reserve_satoshis = 0;
184 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
187 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193 if send_from_initiator {
194 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195 // Note that for outbound channels we have to consider the commitment tx fee and the
196 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197 // well as an additional HTLC.
198 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200 send_payment(&nodes[1], &[&nodes[0]], push_amt);
205 fn test_counterparty_no_reserve() {
206 do_test_counterparty_no_reserve(true);
207 do_test_counterparty_no_reserve(false);
211 fn test_async_inbound_update_fee() {
212 let chanmon_cfgs = create_chanmon_cfgs(2);
213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216 create_announced_chan_between_nodes(&nodes, 0, 1);
219 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
223 // send (1) commitment_signed -.
224 // <- update_add_htlc/commitment_signed
225 // send (2) RAA (awaiting remote revoke) -.
226 // (1) commitment_signed is delivered ->
227 // .- send (3) RAA (awaiting remote revoke)
228 // (2) RAA is delivered ->
229 // .- send (4) commitment_signed
230 // <- (3) RAA is delivered
231 // send (5) commitment_signed -.
232 // <- (4) commitment_signed is delivered
234 // (5) commitment_signed is delivered ->
236 // (6) RAA is delivered ->
238 // First nodes[0] generates an update_fee
240 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
243 nodes[0].node.timer_tick_occurred();
244 check_added_monitors!(nodes[0], 1);
246 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247 assert_eq!(events_0.len(), 1);
248 let (update_msg, commitment_signed) = match events_0[0] { // (1)
249 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250 (update_fee.as_ref(), commitment_signed)
252 _ => panic!("Unexpected event"),
255 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
260 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261 check_added_monitors!(nodes[1], 1);
263 let payment_event = {
264 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265 assert_eq!(events_1.len(), 1);
266 SendEvent::from_event(events_1.remove(0))
268 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269 assert_eq!(payment_event.msgs.len(), 1);
271 // ...now when the messages get delivered everyone should be happy
272 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276 check_added_monitors!(nodes[0], 1);
278 // deliver(1), generate (3):
279 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282 check_added_monitors!(nodes[1], 1);
284 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290 assert!(bs_update.update_fee.is_none()); // (4)
291 check_added_monitors!(nodes[1], 1);
293 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295 assert!(as_update.update_add_htlcs.is_empty()); // (5)
296 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299 assert!(as_update.update_fee.is_none()); // (5)
300 check_added_monitors!(nodes[0], 1);
302 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304 // only (6) so get_event_msg's assert(len == 1) passes
305 check_added_monitors!(nodes[0], 1);
307 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309 check_added_monitors!(nodes[1], 1);
311 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312 check_added_monitors!(nodes[0], 1);
314 let events_2 = nodes[0].node.get_and_clear_pending_events();
315 assert_eq!(events_2.len(), 1);
317 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318 _ => panic!("Unexpected event"),
321 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322 check_added_monitors!(nodes[1], 1);
326 fn test_update_fee_unordered_raa() {
327 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328 // crash in an earlier version of the update_fee patch)
329 let chanmon_cfgs = create_chanmon_cfgs(2);
330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333 create_announced_chan_between_nodes(&nodes, 0, 1);
336 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
338 // First nodes[0] generates an update_fee
340 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
343 nodes[0].node.timer_tick_occurred();
344 check_added_monitors!(nodes[0], 1);
346 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347 assert_eq!(events_0.len(), 1);
348 let update_msg = match events_0[0] { // (1)
349 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
352 _ => panic!("Unexpected event"),
355 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
357 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
360 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
361 check_added_monitors!(nodes[1], 1);
363 let payment_event = {
364 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
365 assert_eq!(events_1.len(), 1);
366 SendEvent::from_event(events_1.remove(0))
368 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
369 assert_eq!(payment_event.msgs.len(), 1);
371 // ...now when the messages get delivered everyone should be happy
372 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
373 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
374 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
376 check_added_monitors!(nodes[0], 1);
378 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
379 check_added_monitors!(nodes[1], 1);
381 // We can't continue, sadly, because our (1) now has a bogus signature
385 fn test_multi_flight_update_fee() {
386 let chanmon_cfgs = create_chanmon_cfgs(2);
387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
389 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
390 create_announced_chan_between_nodes(&nodes, 0, 1);
393 // update_fee/commitment_signed ->
394 // .- send (1) RAA and (2) commitment_signed
395 // update_fee (never committed) ->
397 // We have to manually generate the above update_fee, it is allowed by the protocol but we
398 // don't track which updates correspond to which revoke_and_ack responses so we're in
399 // AwaitingRAA mode and will not generate the update_fee yet.
400 // <- (1) RAA delivered
401 // (3) is generated and send (4) CS -.
402 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
403 // know the per_commitment_point to use for it.
404 // <- (2) commitment_signed delivered
406 // B should send no response here
407 // (4) commitment_signed delivered ->
408 // <- RAA/commitment_signed delivered
411 // First nodes[0] generates an update_fee
414 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
415 initial_feerate = *feerate_lock;
416 *feerate_lock = initial_feerate + 20;
418 nodes[0].node.timer_tick_occurred();
419 check_added_monitors!(nodes[0], 1);
421 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
422 assert_eq!(events_0.len(), 1);
423 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
424 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
425 (update_fee.as_ref().unwrap(), commitment_signed)
427 _ => panic!("Unexpected event"),
430 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
431 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
432 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
433 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
434 check_added_monitors!(nodes[1], 1);
436 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
439 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
440 *feerate_lock = initial_feerate + 40;
442 nodes[0].node.timer_tick_occurred();
443 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
446 // Create the (3) update_fee message that nodes[0] will generate before it does...
447 let mut update_msg_2 = msgs::UpdateFee {
448 channel_id: update_msg_1.channel_id.clone(),
449 feerate_per_kw: (initial_feerate + 30) as u32,
452 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
454 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
456 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
458 // Deliver (1), generating (3) and (4)
459 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
460 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
461 check_added_monitors!(nodes[0], 1);
462 assert!(as_second_update.update_add_htlcs.is_empty());
463 assert!(as_second_update.update_fulfill_htlcs.is_empty());
464 assert!(as_second_update.update_fail_htlcs.is_empty());
465 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
466 // Check that the update_fee newly generated matches what we delivered:
467 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
468 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
470 // Deliver (2) commitment_signed
471 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
472 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
473 check_added_monitors!(nodes[0], 1);
474 // No commitment_signed so get_event_msg's assert(len == 1) passes
476 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
477 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
478 check_added_monitors!(nodes[1], 1);
481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
482 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483 check_added_monitors!(nodes[1], 1);
485 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
486 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
487 check_added_monitors!(nodes[0], 1);
489 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
490 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
491 // No commitment_signed so get_event_msg's assert(len == 1) passes
492 check_added_monitors!(nodes[0], 1);
494 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
495 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
496 check_added_monitors!(nodes[1], 1);
499 fn do_test_sanity_on_in_flight_opens(steps: u8) {
500 // Previously, we had issues deserializing channels when we hadn't connected the first block
501 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
502 // serialization round-trips and simply do steps towards opening a channel and then drop the
505 let chanmon_cfgs = create_chanmon_cfgs(2);
506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
510 if steps & 0b1000_0000 != 0{
511 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
512 connect_block(&nodes[0], &block);
513 connect_block(&nodes[1], &block);
516 if steps & 0x0f == 0 { return; }
517 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
518 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
520 if steps & 0x0f == 1 { return; }
521 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
522 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
524 if steps & 0x0f == 2 { return; }
525 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
527 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
529 if steps & 0x0f == 3 { return; }
530 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
531 check_added_monitors!(nodes[0], 0);
532 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
534 if steps & 0x0f == 4 { return; }
535 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
537 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
538 assert_eq!(added_monitors.len(), 1);
539 assert_eq!(added_monitors[0].0, funding_output);
540 added_monitors.clear();
542 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
544 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
546 if steps & 0x0f == 5 { return; }
547 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
549 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550 assert_eq!(added_monitors.len(), 1);
551 assert_eq!(added_monitors[0].0, funding_output);
552 added_monitors.clear();
555 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
556 let events_4 = nodes[0].node.get_and_clear_pending_events();
557 assert_eq!(events_4.len(), 0);
559 if steps & 0x0f == 6 { return; }
560 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
562 if steps & 0x0f == 7 { return; }
563 confirm_transaction_at(&nodes[0], &tx, 2);
564 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
565 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
566 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
570 fn test_sanity_on_in_flight_opens() {
571 do_test_sanity_on_in_flight_opens(0);
572 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(1);
574 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(2);
576 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(3);
578 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(4);
580 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(5);
582 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(6);
584 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(7);
586 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(8);
588 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
592 fn test_update_fee_vanilla() {
593 let chanmon_cfgs = create_chanmon_cfgs(2);
594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
597 create_announced_chan_between_nodes(&nodes, 0, 1);
600 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
603 nodes[0].node.timer_tick_occurred();
604 check_added_monitors!(nodes[0], 1);
606 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
607 assert_eq!(events_0.len(), 1);
608 let (update_msg, commitment_signed) = match events_0[0] {
609 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
610 (update_fee.as_ref(), commitment_signed)
612 _ => panic!("Unexpected event"),
614 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
616 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
617 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
618 check_added_monitors!(nodes[1], 1);
620 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
621 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
622 check_added_monitors!(nodes[0], 1);
624 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
625 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
626 // No commitment_signed so get_event_msg's assert(len == 1) passes
627 check_added_monitors!(nodes[0], 1);
629 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
630 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
631 check_added_monitors!(nodes[1], 1);
635 fn test_update_fee_that_funder_cannot_afford() {
636 let chanmon_cfgs = create_chanmon_cfgs(2);
637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640 let channel_value = 5000;
642 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
643 let channel_id = chan.2;
644 let secp_ctx = Secp256k1::new();
645 let default_config = UserConfig::default();
646 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
648 let opt_anchors = false;
650 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652 // calculate two different feerates here - the expected local limit as well as the expected
654 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
655 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658 *feerate_lock = feerate;
660 nodes[0].node.timer_tick_occurred();
661 check_added_monitors!(nodes[0], 1);
662 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
664 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
666 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
668 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
670 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
672 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673 assert_eq!(commitment_tx.output.len(), 2);
674 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
675 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676 actual_fee = channel_value - actual_fee;
677 assert_eq!(total_fee, actual_fee);
681 // Increment the feerate by a small constant, accounting for rounding errors
682 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
685 nodes[0].node.timer_tick_occurred();
686 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687 check_added_monitors!(nodes[0], 0);
689 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
691 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692 // needed to sign the new commitment tx and (2) sign the new commitment tx.
693 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
695 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
696 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
697 let chan_signer = local_chan.get_signer();
698 let pubkeys = chan_signer.pubkeys();
699 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
700 pubkeys.funding_pubkey)
702 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
703 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
704 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
705 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
706 let chan_signer = remote_chan.get_signer();
707 let pubkeys = chan_signer.pubkeys();
708 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
709 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
710 pubkeys.funding_pubkey)
713 // Assemble the set of keys we can use for signatures for our commitment_signed message.
714 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
715 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
718 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
719 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
720 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
721 let local_chan_signer = local_chan.get_signer();
722 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
723 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
724 INITIAL_COMMITMENT_NUMBER - 1,
726 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
727 opt_anchors, local_funding, remote_funding,
728 commit_tx_keys.clone(),
729 non_buffer_feerate + 4,
731 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
733 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
736 let commit_signed_msg = msgs::CommitmentSigned {
739 htlc_signatures: res.1,
741 partial_signature_with_nonce: None,
744 let update_fee = msgs::UpdateFee {
746 feerate_per_kw: non_buffer_feerate + 4,
749 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
751 //While producing the commitment_signed response after handling a received update_fee request the
752 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753 //Should produce and error.
754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756 check_added_monitors!(nodes[1], 1);
757 check_closed_broadcast!(nodes[1], true);
758 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
762 fn test_update_fee_with_fundee_update_add_htlc() {
763 let chanmon_cfgs = create_chanmon_cfgs(2);
764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
770 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
773 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
776 nodes[0].node.timer_tick_occurred();
777 check_added_monitors!(nodes[0], 1);
779 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780 assert_eq!(events_0.len(), 1);
781 let (update_msg, commitment_signed) = match events_0[0] {
782 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
783 (update_fee.as_ref(), commitment_signed)
785 _ => panic!("Unexpected event"),
787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 check_added_monitors!(nodes[1], 1);
792 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
794 // nothing happens since node[1] is in AwaitingRemoteRevoke
795 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
796 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
798 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799 assert_eq!(added_monitors.len(), 0);
800 added_monitors.clear();
802 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804 // node[1] has nothing to do
806 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808 check_added_monitors!(nodes[0], 1);
810 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812 // No commitment_signed so get_event_msg's assert(len == 1) passes
813 check_added_monitors!(nodes[0], 1);
814 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815 check_added_monitors!(nodes[1], 1);
816 // AwaitingRemoteRevoke ends here
818 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823 assert_eq!(commitment_update.update_fee.is_none(), true);
825 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827 check_added_monitors!(nodes[0], 1);
828 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831 check_added_monitors!(nodes[1], 1);
832 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
834 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835 check_added_monitors!(nodes[1], 1);
836 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837 // No commitment_signed so get_event_msg's assert(len == 1) passes
839 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840 check_added_monitors!(nodes[0], 1);
841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
843 expect_pending_htlcs_forwardable!(nodes[0]);
845 let events = nodes[0].node.get_and_clear_pending_events();
846 assert_eq!(events.len(), 1);
848 Event::PaymentClaimable { .. } => { },
849 _ => panic!("Unexpected event"),
852 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
854 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
862 fn test_update_fee() {
863 let chanmon_cfgs = create_chanmon_cfgs(2);
864 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868 let channel_id = chan.2;
871 // (1) update_fee/commitment_signed ->
872 // <- (2) revoke_and_ack
873 // .- send (3) commitment_signed
874 // (4) update_fee/commitment_signed ->
875 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876 // <- (3) commitment_signed delivered
877 // send (6) revoke_and_ack -.
878 // <- (5) deliver revoke_and_ack
879 // (6) deliver revoke_and_ack ->
880 // .- send (7) commitment_signed in response to (4)
881 // <- (7) deliver commitment_signed
884 // Create and deliver (1)...
887 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888 feerate = *feerate_lock;
889 *feerate_lock = feerate + 20;
891 nodes[0].node.timer_tick_occurred();
892 check_added_monitors!(nodes[0], 1);
894 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895 assert_eq!(events_0.len(), 1);
896 let (update_msg, commitment_signed) = match events_0[0] {
897 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
898 (update_fee.as_ref(), commitment_signed)
900 _ => panic!("Unexpected event"),
902 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
904 // Generate (2) and (3):
905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907 check_added_monitors!(nodes[1], 1);
910 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912 check_added_monitors!(nodes[0], 1);
914 // Create and deliver (4)...
916 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917 *feerate_lock = feerate + 30;
919 nodes[0].node.timer_tick_occurred();
920 check_added_monitors!(nodes[0], 1);
921 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922 assert_eq!(events_0.len(), 1);
923 let (update_msg, commitment_signed) = match events_0[0] {
924 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
925 (update_fee.as_ref(), commitment_signed)
927 _ => panic!("Unexpected event"),
930 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932 check_added_monitors!(nodes[1], 1);
934 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935 // No commitment_signed so get_event_msg's assert(len == 1) passes
937 // Handle (3), creating (6):
938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939 check_added_monitors!(nodes[0], 1);
940 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941 // No commitment_signed so get_event_msg's assert(len == 1) passes
944 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946 check_added_monitors!(nodes[0], 1);
948 // Deliver (6), creating (7):
949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951 assert!(commitment_update.update_add_htlcs.is_empty());
952 assert!(commitment_update.update_fulfill_htlcs.is_empty());
953 assert!(commitment_update.update_fail_htlcs.is_empty());
954 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955 assert!(commitment_update.update_fee.is_none());
956 check_added_monitors!(nodes[1], 1);
959 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960 check_added_monitors!(nodes[0], 1);
961 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962 // No commitment_signed so get_event_msg's assert(len == 1) passes
964 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965 check_added_monitors!(nodes[1], 1);
966 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
968 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
976 fn fake_network_test() {
977 // Simple test which builds a network of ChannelManagers, connects them to each other, and
978 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979 let chanmon_cfgs = create_chanmon_cfgs(4);
980 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
984 // Create some initial channels
985 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
989 // Rebalance the network a bit by relaying one payment through all the channels...
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995 // Send some more payments
996 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1000 // Test failure packets
1001 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1004 // Add a new channel that skips 3
1005 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1007 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1009 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015 // Do some rebalance loop payments, simultaneously
1016 let mut hops = Vec::with_capacity(3);
1017 hops.push(RouteHop {
1018 pubkey: nodes[2].node.get_our_node_id(),
1019 node_features: NodeFeatures::empty(),
1020 short_channel_id: chan_2.0.contents.short_channel_id,
1021 channel_features: ChannelFeatures::empty(),
1023 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1025 hops.push(RouteHop {
1026 pubkey: nodes[3].node.get_our_node_id(),
1027 node_features: NodeFeatures::empty(),
1028 short_channel_id: chan_3.0.contents.short_channel_id,
1029 channel_features: ChannelFeatures::empty(),
1031 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1033 hops.push(RouteHop {
1034 pubkey: nodes[1].node.get_our_node_id(),
1035 node_features: nodes[1].node.node_features(),
1036 short_channel_id: chan_4.0.contents.short_channel_id,
1037 channel_features: nodes[1].node.channel_features(),
1039 cltv_expiry_delta: TEST_FINAL_CLTV,
1041 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1042 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1043 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1045 let mut hops = Vec::with_capacity(3);
1046 hops.push(RouteHop {
1047 pubkey: nodes[3].node.get_our_node_id(),
1048 node_features: NodeFeatures::empty(),
1049 short_channel_id: chan_4.0.contents.short_channel_id,
1050 channel_features: ChannelFeatures::empty(),
1052 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1054 hops.push(RouteHop {
1055 pubkey: nodes[2].node.get_our_node_id(),
1056 node_features: NodeFeatures::empty(),
1057 short_channel_id: chan_3.0.contents.short_channel_id,
1058 channel_features: ChannelFeatures::empty(),
1060 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1062 hops.push(RouteHop {
1063 pubkey: nodes[1].node.get_our_node_id(),
1064 node_features: nodes[1].node.node_features(),
1065 short_channel_id: chan_2.0.contents.short_channel_id,
1066 channel_features: nodes[1].node.channel_features(),
1068 cltv_expiry_delta: TEST_FINAL_CLTV,
1070 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1071 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1072 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1074 // Claim the rebalances...
1075 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1078 // Close down the channels...
1079 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 fn holding_cell_htlc_counting() {
1095 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097 // commitment dance rounds.
1098 let chanmon_cfgs = create_chanmon_cfgs(3);
1099 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102 create_announced_chan_between_nodes(&nodes, 0, 1);
1103 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1105 // Fetch a route in advance as we will be unable to once we're unable to send.
1106 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108 let mut payments = Vec::new();
1110 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111 nodes[1].node.send_payment_with_route(&route, payment_hash,
1112 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1113 payments.push((payment_preimage, payment_hash));
1115 check_added_monitors!(nodes[1], 1);
1117 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1118 assert_eq!(events.len(), 1);
1119 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1120 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1122 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1123 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1126 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1127 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1128 ), true, APIError::ChannelUnavailable { ref err },
1129 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1130 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1131 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1134 // This should also be true if we try to forward a payment.
1135 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1137 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1138 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1139 check_added_monitors!(nodes[0], 1);
1142 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1143 assert_eq!(events.len(), 1);
1144 let payment_event = SendEvent::from_event(events.pop().unwrap());
1145 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1147 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1148 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1149 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1150 // fails), the second will process the resulting failure and fail the HTLC backward.
1151 expect_pending_htlcs_forwardable!(nodes[1]);
1152 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1153 check_added_monitors!(nodes[1], 1);
1155 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1156 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1157 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1159 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1161 // Now forward all the pending HTLCs and claim them back
1162 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1163 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1164 check_added_monitors!(nodes[2], 1);
1166 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168 check_added_monitors!(nodes[1], 1);
1169 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1171 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1172 check_added_monitors!(nodes[1], 1);
1173 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1175 for ref update in as_updates.update_add_htlcs.iter() {
1176 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1178 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1179 check_added_monitors!(nodes[2], 1);
1180 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1181 check_added_monitors!(nodes[2], 1);
1182 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1184 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1185 check_added_monitors!(nodes[1], 1);
1186 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1187 check_added_monitors!(nodes[1], 1);
1188 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1190 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1191 check_added_monitors!(nodes[2], 1);
1193 expect_pending_htlcs_forwardable!(nodes[2]);
1195 let events = nodes[2].node.get_and_clear_pending_events();
1196 assert_eq!(events.len(), payments.len());
1197 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1199 &Event::PaymentClaimable { ref payment_hash, .. } => {
1200 assert_eq!(*payment_hash, *hash);
1202 _ => panic!("Unexpected event"),
1206 for (preimage, _) in payments.drain(..) {
1207 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1210 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1214 fn duplicate_htlc_test() {
1215 // Test that we accept duplicate payment_hash HTLCs across the network and that
1216 // claiming/failing them are all separate and don't affect each other
1217 let chanmon_cfgs = create_chanmon_cfgs(6);
1218 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1219 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1220 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1222 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1223 create_announced_chan_between_nodes(&nodes, 0, 3);
1224 create_announced_chan_between_nodes(&nodes, 1, 3);
1225 create_announced_chan_between_nodes(&nodes, 2, 3);
1226 create_announced_chan_between_nodes(&nodes, 3, 4);
1227 create_announced_chan_between_nodes(&nodes, 3, 5);
1229 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1231 *nodes[0].network_payment_count.borrow_mut() -= 1;
1232 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1234 *nodes[0].network_payment_count.borrow_mut() -= 1;
1235 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1237 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1238 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1239 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1243 fn test_duplicate_htlc_different_direction_onchain() {
1244 // Test that ChannelMonitor doesn't generate 2 preimage txn
1245 // when we have 2 HTLCs with same preimage that go across a node
1246 // in opposite directions, even with the same payment secret.
1247 let chanmon_cfgs = create_chanmon_cfgs(2);
1248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1250 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1252 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1255 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1257 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1259 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1260 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1261 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1263 // Provide preimage to node 0 by claiming payment
1264 nodes[0].node.claim_funds(payment_preimage);
1265 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1266 check_added_monitors!(nodes[0], 1);
1268 // Broadcast node 1 commitment txn
1269 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1271 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1272 let mut has_both_htlcs = 0; // check htlcs match ones committed
1273 for outp in remote_txn[0].output.iter() {
1274 if outp.value == 800_000 / 1000 {
1275 has_both_htlcs += 1;
1276 } else if outp.value == 900_000 / 1000 {
1277 has_both_htlcs += 1;
1280 assert_eq!(has_both_htlcs, 2);
1282 mine_transaction(&nodes[0], &remote_txn[0]);
1283 check_added_monitors!(nodes[0], 1);
1284 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1285 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1287 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1288 assert_eq!(claim_txn.len(), 3);
1290 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1291 check_spends!(claim_txn[1], remote_txn[0]);
1292 check_spends!(claim_txn[2], remote_txn[0]);
1293 let preimage_tx = &claim_txn[0];
1294 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1295 (&claim_txn[1], &claim_txn[2])
1297 (&claim_txn[2], &claim_txn[1])
1300 assert_eq!(preimage_tx.input.len(), 1);
1301 assert_eq!(preimage_bump_tx.input.len(), 1);
1303 assert_eq!(preimage_tx.input.len(), 1);
1304 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1305 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1307 assert_eq!(timeout_tx.input.len(), 1);
1308 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1309 check_spends!(timeout_tx, remote_txn[0]);
1310 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1312 let events = nodes[0].node.get_and_clear_pending_msg_events();
1313 assert_eq!(events.len(), 3);
1316 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1317 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1318 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1319 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1321 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1322 assert!(update_add_htlcs.is_empty());
1323 assert!(update_fail_htlcs.is_empty());
1324 assert_eq!(update_fulfill_htlcs.len(), 1);
1325 assert!(update_fail_malformed_htlcs.is_empty());
1326 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1328 _ => panic!("Unexpected event"),
1334 fn test_basic_channel_reserve() {
1335 let chanmon_cfgs = create_chanmon_cfgs(2);
1336 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1337 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1338 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1339 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1341 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1342 let channel_reserve = chan_stat.channel_reserve_msat;
1344 // The 2* and +1 are for the fee spike reserve.
1345 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1346 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1347 let (mut route, our_payment_hash, _, our_payment_secret) =
1348 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1349 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1350 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1351 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1353 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1355 &APIError::ChannelUnavailable{ref err} =>
1356 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1357 _ => panic!("Unexpected error variant"),
1360 _ => panic!("Unexpected error variant"),
1362 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1363 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1365 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1369 fn test_fee_spike_violation_fails_htlc() {
1370 let chanmon_cfgs = create_chanmon_cfgs(2);
1371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1373 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1374 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1376 let (mut route, payment_hash, _, payment_secret) =
1377 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1378 route.paths[0].hops[0].fee_msat += 1;
1379 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1380 let secp_ctx = Secp256k1::new();
1381 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1383 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1385 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1386 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1387 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1388 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1389 let msg = msgs::UpdateAddHTLC {
1392 amount_msat: htlc_msat,
1393 payment_hash: payment_hash,
1394 cltv_expiry: htlc_cltv,
1395 onion_routing_packet: onion_packet,
1398 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1400 // Now manually create the commitment_signed message corresponding to the update_add
1401 // nodes[0] just sent. In the code for construction of this message, "local" refers
1402 // to the sender of the message, and "remote" refers to the receiver.
1404 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1406 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1408 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1409 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1410 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1411 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1412 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1413 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1414 let chan_signer = local_chan.get_signer();
1415 // Make the signer believe we validated another commitment, so we can release the secret
1416 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1418 let pubkeys = chan_signer.pubkeys();
1419 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1420 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1421 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1422 chan_signer.pubkeys().funding_pubkey)
1424 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1425 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1426 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1427 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1428 let chan_signer = remote_chan.get_signer();
1429 let pubkeys = chan_signer.pubkeys();
1430 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1431 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1432 chan_signer.pubkeys().funding_pubkey)
1435 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1436 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1437 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1439 // Build the remote commitment transaction so we can sign it, and then later use the
1440 // signature for the commitment_signed message.
1441 let local_chan_balance = 1313;
1443 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1445 amount_msat: 3460001,
1446 cltv_expiry: htlc_cltv,
1448 transaction_output_index: Some(1),
1451 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1454 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1455 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1456 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1457 let local_chan_signer = local_chan.get_signer();
1458 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1462 local_chan.opt_anchors(), local_funding, remote_funding,
1463 commit_tx_keys.clone(),
1465 &mut vec![(accepted_htlc_info, ())],
1466 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1468 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1471 let commit_signed_msg = msgs::CommitmentSigned {
1474 htlc_signatures: res.1,
1476 partial_signature_with_nonce: None,
1479 // Send the commitment_signed message to the nodes[1].
1480 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1481 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1483 // Send the RAA to nodes[1].
1484 let raa_msg = msgs::RevokeAndACK {
1486 per_commitment_secret: local_secret,
1487 next_per_commitment_point: next_local_point,
1489 next_local_nonce: None,
1491 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1493 let events = nodes[1].node.get_and_clear_pending_msg_events();
1494 assert_eq!(events.len(), 1);
1495 // Make sure the HTLC failed in the way we expect.
1497 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1498 assert_eq!(update_fail_htlcs.len(), 1);
1499 update_fail_htlcs[0].clone()
1501 _ => panic!("Unexpected event"),
1503 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1504 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1506 check_added_monitors!(nodes[1], 2);
1510 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1511 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1512 // Set the fee rate for the channel very high, to the point where the fundee
1513 // sending any above-dust amount would result in a channel reserve violation.
1514 // In this test we check that we would be prevented from sending an HTLC in
1516 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1519 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1520 let default_config = UserConfig::default();
1521 let opt_anchors = false;
1523 let mut push_amt = 100_000_000;
1524 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1526 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1528 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1530 // Fetch a route in advance as we will be unable to once we're unable to send.
1531 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1532 // Sending exactly enough to hit the reserve amount should be accepted
1533 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1534 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1537 // However one more HTLC should be significantly over the reserve amount and fail.
1538 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1539 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1540 ), true, APIError::ChannelUnavailable { ref err },
1541 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1542 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1543 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1547 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1548 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1549 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1550 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1551 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1552 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1553 let default_config = UserConfig::default();
1554 let opt_anchors = false;
1556 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1557 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1558 // transaction fee with 0 HTLCs (183 sats)).
1559 let mut push_amt = 100_000_000;
1560 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1561 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1562 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1564 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1565 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1566 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1569 let (mut route, payment_hash, _, payment_secret) =
1570 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1571 route.paths[0].hops[0].fee_msat = 700_000;
1572 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1573 let secp_ctx = Secp256k1::new();
1574 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1575 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1576 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1577 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1578 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1579 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1580 let msg = msgs::UpdateAddHTLC {
1582 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1583 amount_msat: htlc_msat,
1584 payment_hash: payment_hash,
1585 cltv_expiry: htlc_cltv,
1586 onion_routing_packet: onion_packet,
1589 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1590 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1591 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1592 assert_eq!(nodes[0].node.list_channels().len(), 0);
1593 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1594 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1595 check_added_monitors!(nodes[0], 1);
1596 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1600 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1601 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1602 // calculating our commitment transaction fee (this was previously broken).
1603 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1604 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1608 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1609 let default_config = UserConfig::default();
1610 let opt_anchors = false;
1612 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1613 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1614 // transaction fee with 0 HTLCs (183 sats)).
1615 let mut push_amt = 100_000_000;
1616 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1617 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1618 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1620 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1621 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1622 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1623 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1624 // commitment transaction fee.
1625 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1627 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1628 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1629 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1632 // One more than the dust amt should fail, however.
1633 let (mut route, our_payment_hash, _, our_payment_secret) =
1634 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1635 route.paths[0].hops[0].fee_msat += 1;
1636 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1637 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1638 ), true, APIError::ChannelUnavailable { ref err },
1639 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1643 fn test_chan_init_feerate_unaffordability() {
1644 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1645 // channel reserve and feerate requirements.
1646 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1647 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1648 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1649 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1650 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1651 let default_config = UserConfig::default();
1652 let opt_anchors = false;
1654 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1656 let mut push_amt = 100_000_000;
1657 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1658 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1659 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1661 // During open, we don't have a "counterparty channel reserve" to check against, so that
1662 // requirement only comes into play on the open_channel handling side.
1663 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1664 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1665 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1666 open_channel_msg.push_msat += 1;
1667 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1669 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1670 assert_eq!(msg_events.len(), 1);
1671 match msg_events[0] {
1672 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1673 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1675 _ => panic!("Unexpected event"),
1680 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1681 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1682 // calculating our counterparty's commitment transaction fee (this was previously broken).
1683 let chanmon_cfgs = create_chanmon_cfgs(2);
1684 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1685 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1686 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1687 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1689 let payment_amt = 46000; // Dust amount
1690 // In the previous code, these first four payments would succeed.
1691 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1697 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1703 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1704 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1705 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1706 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1710 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1711 let chanmon_cfgs = create_chanmon_cfgs(3);
1712 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1713 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1714 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1715 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1716 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1719 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1720 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1721 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1722 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1724 // Add a 2* and +1 for the fee spike reserve.
1725 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1726 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;
1727 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1729 // Add a pending HTLC.
1730 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1731 let payment_event_1 = {
1732 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1733 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1734 check_added_monitors!(nodes[0], 1);
1736 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1737 assert_eq!(events.len(), 1);
1738 SendEvent::from_event(events.remove(0))
1740 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1742 // Attempt to trigger a channel reserve violation --> payment failure.
1743 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1744 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;
1745 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1746 let mut route_2 = route_1.clone();
1747 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1749 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1750 let secp_ctx = Secp256k1::new();
1751 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1752 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1753 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1754 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1755 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1756 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1757 let msg = msgs::UpdateAddHTLC {
1760 amount_msat: htlc_msat + 1,
1761 payment_hash: our_payment_hash_1,
1762 cltv_expiry: htlc_cltv,
1763 onion_routing_packet: onion_packet,
1766 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1767 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1768 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1769 assert_eq!(nodes[1].node.list_channels().len(), 1);
1770 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1771 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1772 check_added_monitors!(nodes[1], 1);
1773 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1777 fn test_inbound_outbound_capacity_is_not_zero() {
1778 let chanmon_cfgs = create_chanmon_cfgs(2);
1779 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1780 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1781 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1782 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1783 let channels0 = node_chanmgrs[0].list_channels();
1784 let channels1 = node_chanmgrs[1].list_channels();
1785 let default_config = UserConfig::default();
1786 assert_eq!(channels0.len(), 1);
1787 assert_eq!(channels1.len(), 1);
1789 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1790 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1791 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1793 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1794 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1797 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1798 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1802 fn test_channel_reserve_holding_cell_htlcs() {
1803 let chanmon_cfgs = create_chanmon_cfgs(3);
1804 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1805 // When this test was written, the default base fee floated based on the HTLC count.
1806 // It is now fixed, so we simply set the fee to the expected value here.
1807 let mut config = test_default_channel_config();
1808 config.channel_config.forwarding_fee_base_msat = 239;
1809 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1810 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1811 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1812 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1814 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1815 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1817 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1818 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1820 macro_rules! expect_forward {
1822 let mut events = $node.node.get_and_clear_pending_msg_events();
1823 assert_eq!(events.len(), 1);
1824 check_added_monitors!($node, 1);
1825 let payment_event = SendEvent::from_event(events.remove(0));
1830 let feemsat = 239; // set above
1831 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1832 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1833 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1835 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1837 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1839 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1840 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1841 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1842 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1843 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1845 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1846 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1847 ), true, APIError::ChannelUnavailable { ref err },
1848 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1849 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1850 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
1853 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1854 // nodes[0]'s wealth
1856 let amt_msat = recv_value_0 + total_fee_msat;
1857 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1858 // Also, ensure that each payment has enough to be over the dust limit to
1859 // ensure it'll be included in each commit tx fee calculation.
1860 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1861 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1862 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1866 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1867 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1868 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1869 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1870 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1872 let (stat01_, stat11_, stat12_, stat22_) = (
1873 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1874 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1875 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1876 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1879 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1880 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1881 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1882 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1883 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1886 // adding pending output.
1887 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1888 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1889 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1890 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1891 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1892 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1893 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1894 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1895 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1897 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1898 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1899 let amt_msat_1 = recv_value_1 + total_fee_msat;
1901 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);
1902 let payment_event_1 = {
1903 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1904 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1905 check_added_monitors!(nodes[0], 1);
1907 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1908 assert_eq!(events.len(), 1);
1909 SendEvent::from_event(events.remove(0))
1911 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1913 // channel reserve test with htlc pending output > 0
1914 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1916 let mut route = route_1.clone();
1917 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1918 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1919 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1920 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1921 ), true, APIError::ChannelUnavailable { ref err },
1922 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1923 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1926 // split the rest to test holding cell
1927 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1928 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1929 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1930 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1932 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1933 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);
1936 // now see if they go through on both sides
1937 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);
1938 // but this will stuck in the holding cell
1939 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1940 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1941 check_added_monitors!(nodes[0], 0);
1942 let events = nodes[0].node.get_and_clear_pending_events();
1943 assert_eq!(events.len(), 0);
1945 // test with outbound holding cell amount > 0
1947 let (mut route, our_payment_hash, _, our_payment_secret) =
1948 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1949 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1950 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1951 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1952 ), true, APIError::ChannelUnavailable { ref err },
1953 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1954 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1955 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1958 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);
1959 // this will also stuck in the holding cell
1960 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1961 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1962 check_added_monitors!(nodes[0], 0);
1963 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1964 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1966 // flush the pending htlc
1967 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1968 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1969 check_added_monitors!(nodes[1], 1);
1971 // the pending htlc should be promoted to committed
1972 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1973 check_added_monitors!(nodes[0], 1);
1974 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1976 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1977 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1978 // No commitment_signed so get_event_msg's assert(len == 1) passes
1979 check_added_monitors!(nodes[0], 1);
1981 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1982 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1983 check_added_monitors!(nodes[1], 1);
1985 expect_pending_htlcs_forwardable!(nodes[1]);
1987 let ref payment_event_11 = expect_forward!(nodes[1]);
1988 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1989 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1991 expect_pending_htlcs_forwardable!(nodes[2]);
1992 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1994 // flush the htlcs in the holding cell
1995 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1996 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1997 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1998 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1999 expect_pending_htlcs_forwardable!(nodes[1]);
2001 let ref payment_event_3 = expect_forward!(nodes[1]);
2002 assert_eq!(payment_event_3.msgs.len(), 2);
2003 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2004 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2006 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2007 expect_pending_htlcs_forwardable!(nodes[2]);
2009 let events = nodes[2].node.get_and_clear_pending_events();
2010 assert_eq!(events.len(), 2);
2012 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2013 assert_eq!(our_payment_hash_21, *payment_hash);
2014 assert_eq!(recv_value_21, amount_msat);
2015 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2016 assert_eq!(via_channel_id, Some(chan_2.2));
2018 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2019 assert!(payment_preimage.is_none());
2020 assert_eq!(our_payment_secret_21, *payment_secret);
2022 _ => panic!("expected PaymentPurpose::InvoicePayment")
2025 _ => panic!("Unexpected event"),
2028 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2029 assert_eq!(our_payment_hash_22, *payment_hash);
2030 assert_eq!(recv_value_22, amount_msat);
2031 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2032 assert_eq!(via_channel_id, Some(chan_2.2));
2034 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2035 assert!(payment_preimage.is_none());
2036 assert_eq!(our_payment_secret_22, *payment_secret);
2038 _ => panic!("expected PaymentPurpose::InvoicePayment")
2041 _ => panic!("Unexpected event"),
2044 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2045 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2046 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2048 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2049 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2050 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2052 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2053 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);
2054 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2055 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2056 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2058 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2059 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2063 fn channel_reserve_in_flight_removes() {
2064 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2065 // can send to its counterparty, but due to update ordering, the other side may not yet have
2066 // considered those HTLCs fully removed.
2067 // This tests that we don't count HTLCs which will not be included in the next remote
2068 // commitment transaction towards the reserve value (as it implies no commitment transaction
2069 // will be generated which violates the remote reserve value).
2070 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2072 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2073 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2074 // you only consider the value of the first HTLC, it may not),
2075 // * start routing a third HTLC from A to B,
2076 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2077 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2078 // * deliver the first fulfill from B
2079 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2081 // * deliver A's response CS and RAA.
2082 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2083 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2084 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2085 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2086 let chanmon_cfgs = create_chanmon_cfgs(2);
2087 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2088 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2089 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2090 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2092 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2093 // Route the first two HTLCs.
2094 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2095 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2096 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2098 // Start routing the third HTLC (this is just used to get everyone in the right state).
2099 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2101 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2102 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2103 check_added_monitors!(nodes[0], 1);
2104 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2105 assert_eq!(events.len(), 1);
2106 SendEvent::from_event(events.remove(0))
2109 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2110 // initial fulfill/CS.
2111 nodes[1].node.claim_funds(payment_preimage_1);
2112 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2113 check_added_monitors!(nodes[1], 1);
2114 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2116 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2117 // remove the second HTLC when we send the HTLC back from B to A.
2118 nodes[1].node.claim_funds(payment_preimage_2);
2119 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2120 check_added_monitors!(nodes[1], 1);
2121 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2123 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2124 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2125 check_added_monitors!(nodes[0], 1);
2126 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2127 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2129 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2130 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2131 check_added_monitors!(nodes[1], 1);
2132 // B is already AwaitingRAA, so cant generate a CS here
2133 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2135 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2136 check_added_monitors!(nodes[1], 1);
2137 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2139 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2140 check_added_monitors!(nodes[0], 1);
2141 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2143 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144 check_added_monitors!(nodes[1], 1);
2145 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2147 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2148 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2149 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2150 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2151 // on-chain as necessary).
2152 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2153 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2154 check_added_monitors!(nodes[0], 1);
2155 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2156 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2158 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2159 check_added_monitors!(nodes[1], 1);
2160 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2162 expect_pending_htlcs_forwardable!(nodes[1]);
2163 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2165 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2166 // resolve the second HTLC from A's point of view.
2167 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2168 check_added_monitors!(nodes[0], 1);
2169 expect_payment_path_successful!(nodes[0]);
2170 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2172 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2173 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2174 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2176 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2177 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2178 check_added_monitors!(nodes[1], 1);
2179 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2180 assert_eq!(events.len(), 1);
2181 SendEvent::from_event(events.remove(0))
2184 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2185 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2186 check_added_monitors!(nodes[0], 1);
2187 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2189 // Now just resolve all the outstanding messages/HTLCs for completeness...
2191 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2192 check_added_monitors!(nodes[1], 1);
2193 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2195 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2196 check_added_monitors!(nodes[1], 1);
2198 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2199 check_added_monitors!(nodes[0], 1);
2200 expect_payment_path_successful!(nodes[0]);
2201 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2203 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2204 check_added_monitors!(nodes[1], 1);
2205 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2207 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2208 check_added_monitors!(nodes[0], 1);
2210 expect_pending_htlcs_forwardable!(nodes[0]);
2211 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2213 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2214 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2218 fn channel_monitor_network_test() {
2219 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2220 // tests that ChannelMonitor is able to recover from various states.
2221 let chanmon_cfgs = create_chanmon_cfgs(5);
2222 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2223 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2224 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2226 // Create some initial channels
2227 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2228 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2229 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2230 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2232 // Make sure all nodes are at the same starting height
2233 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2234 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2235 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2236 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2237 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2239 // Rebalance the network a bit by relaying one payment through all the channels...
2240 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2241 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2242 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2243 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2245 // Simple case with no pending HTLCs:
2246 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2247 check_added_monitors!(nodes[1], 1);
2248 check_closed_broadcast!(nodes[1], true);
2250 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2251 assert_eq!(node_txn.len(), 1);
2252 mine_transaction(&nodes[0], &node_txn[0]);
2253 check_added_monitors!(nodes[0], 1);
2254 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2256 check_closed_broadcast!(nodes[0], true);
2257 assert_eq!(nodes[0].node.list_channels().len(), 0);
2258 assert_eq!(nodes[1].node.list_channels().len(), 1);
2259 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2260 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2262 // One pending HTLC is discarded by the force-close:
2263 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2265 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2266 // broadcasted until we reach the timelock time).
2267 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2268 check_closed_broadcast!(nodes[1], true);
2269 check_added_monitors!(nodes[1], 1);
2271 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2272 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2273 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2274 mine_transaction(&nodes[2], &node_txn[0]);
2275 check_added_monitors!(nodes[2], 1);
2276 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2278 check_closed_broadcast!(nodes[2], true);
2279 assert_eq!(nodes[1].node.list_channels().len(), 0);
2280 assert_eq!(nodes[2].node.list_channels().len(), 1);
2281 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2282 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2284 macro_rules! claim_funds {
2285 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2287 $node.node.claim_funds($preimage);
2288 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2289 check_added_monitors!($node, 1);
2291 let events = $node.node.get_and_clear_pending_msg_events();
2292 assert_eq!(events.len(), 1);
2294 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2295 assert!(update_add_htlcs.is_empty());
2296 assert!(update_fail_htlcs.is_empty());
2297 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2299 _ => panic!("Unexpected event"),
2305 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2306 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2307 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2308 check_added_monitors!(nodes[2], 1);
2309 check_closed_broadcast!(nodes[2], true);
2310 let node2_commitment_txid;
2312 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2313 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2314 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2315 node2_commitment_txid = node_txn[0].txid();
2317 // Claim the payment on nodes[3], giving it knowledge of the preimage
2318 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2319 mine_transaction(&nodes[3], &node_txn[0]);
2320 check_added_monitors!(nodes[3], 1);
2321 check_preimage_claim(&nodes[3], &node_txn);
2323 check_closed_broadcast!(nodes[3], true);
2324 assert_eq!(nodes[2].node.list_channels().len(), 0);
2325 assert_eq!(nodes[3].node.list_channels().len(), 1);
2326 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2327 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2329 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2330 // confusing us in the following tests.
2331 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2333 // One pending HTLC to time out:
2334 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2335 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2338 let (close_chan_update_1, close_chan_update_2) = {
2339 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2340 let events = nodes[3].node.get_and_clear_pending_msg_events();
2341 assert_eq!(events.len(), 2);
2342 let close_chan_update_1 = match events[0] {
2343 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2346 _ => panic!("Unexpected event"),
2349 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2350 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2352 _ => panic!("Unexpected event"),
2354 check_added_monitors!(nodes[3], 1);
2356 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2358 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2359 node_txn.retain(|tx| {
2360 if tx.input[0].previous_output.txid == node2_commitment_txid {
2366 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2368 // Claim the payment on nodes[4], giving it knowledge of the preimage
2369 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2371 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2372 let events = nodes[4].node.get_and_clear_pending_msg_events();
2373 assert_eq!(events.len(), 2);
2374 let close_chan_update_2 = match events[0] {
2375 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2378 _ => panic!("Unexpected event"),
2381 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2382 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2384 _ => panic!("Unexpected event"),
2386 check_added_monitors!(nodes[4], 1);
2387 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2389 mine_transaction(&nodes[4], &node_txn[0]);
2390 check_preimage_claim(&nodes[4], &node_txn);
2391 (close_chan_update_1, close_chan_update_2)
2393 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2394 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2395 assert_eq!(nodes[3].node.list_channels().len(), 0);
2396 assert_eq!(nodes[4].node.list_channels().len(), 0);
2398 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2399 ChannelMonitorUpdateStatus::Completed);
2400 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2401 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2405 fn test_justice_tx_htlc_timeout() {
2406 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2407 let mut alice_config = UserConfig::default();
2408 alice_config.channel_handshake_config.announced_channel = true;
2409 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2410 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2411 let mut bob_config = UserConfig::default();
2412 bob_config.channel_handshake_config.announced_channel = true;
2413 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2414 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2415 let user_cfgs = [Some(alice_config), Some(bob_config)];
2416 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2417 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2418 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2419 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2420 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2421 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2422 // Create some new channels:
2423 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2425 // A pending HTLC which will be revoked:
2426 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2427 // Get the will-be-revoked local txn from nodes[0]
2428 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2429 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2430 assert_eq!(revoked_local_txn[0].input.len(), 1);
2431 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2432 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2433 assert_eq!(revoked_local_txn[1].input.len(), 1);
2434 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2435 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2436 // Revoke the old state
2437 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2440 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2442 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2444 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2445 check_spends!(node_txn[0], revoked_local_txn[0]);
2446 node_txn.swap_remove(0);
2448 check_added_monitors!(nodes[1], 1);
2449 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2450 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2452 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2453 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2454 // Verify broadcast of revoked HTLC-timeout
2455 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2456 check_added_monitors!(nodes[0], 1);
2457 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2458 // Broadcast revoked HTLC-timeout on node 1
2459 mine_transaction(&nodes[1], &node_txn[1]);
2460 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2462 get_announce_close_broadcast_events(&nodes, 0, 1);
2463 assert_eq!(nodes[0].node.list_channels().len(), 0);
2464 assert_eq!(nodes[1].node.list_channels().len(), 0);
2468 fn test_justice_tx_htlc_success() {
2469 // Test justice txn built on revoked HTLC-Success tx, against both sides
2470 let mut alice_config = UserConfig::default();
2471 alice_config.channel_handshake_config.announced_channel = true;
2472 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2473 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2474 let mut bob_config = UserConfig::default();
2475 bob_config.channel_handshake_config.announced_channel = true;
2476 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2477 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2478 let user_cfgs = [Some(alice_config), Some(bob_config)];
2479 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2480 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2481 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2484 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2485 // Create some new channels:
2486 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2488 // A pending HTLC which will be revoked:
2489 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2490 // Get the will-be-revoked local txn from B
2491 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2492 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2493 assert_eq!(revoked_local_txn[0].input.len(), 1);
2494 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2495 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2496 // Revoke the old state
2497 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2499 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2501 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2502 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2503 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2505 check_spends!(node_txn[0], revoked_local_txn[0]);
2506 node_txn.swap_remove(0);
2508 check_added_monitors!(nodes[0], 1);
2509 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2511 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2512 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2513 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2514 check_added_monitors!(nodes[1], 1);
2515 mine_transaction(&nodes[0], &node_txn[1]);
2516 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2517 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2519 get_announce_close_broadcast_events(&nodes, 0, 1);
2520 assert_eq!(nodes[0].node.list_channels().len(), 0);
2521 assert_eq!(nodes[1].node.list_channels().len(), 0);
2525 fn revoked_output_claim() {
2526 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2527 // transaction is broadcast by its counterparty
2528 let chanmon_cfgs = create_chanmon_cfgs(2);
2529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2531 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2532 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2533 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2534 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2535 assert_eq!(revoked_local_txn.len(), 1);
2536 // Only output is the full channel value back to nodes[0]:
2537 assert_eq!(revoked_local_txn[0].output.len(), 1);
2538 // Send a payment through, updating everyone's latest commitment txn
2539 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2541 // Inform nodes[1] that nodes[0] broadcast a stale tx
2542 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2543 check_added_monitors!(nodes[1], 1);
2544 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2545 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2546 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2548 check_spends!(node_txn[0], revoked_local_txn[0]);
2550 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2551 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2552 get_announce_close_broadcast_events(&nodes, 0, 1);
2553 check_added_monitors!(nodes[0], 1);
2554 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2558 fn claim_htlc_outputs_shared_tx() {
2559 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2560 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2561 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2564 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2566 // Create some new channel:
2567 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2569 // Rebalance the network to generate htlc in the two directions
2570 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2571 // 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
2572 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2573 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2575 // Get the will-be-revoked local txn from node[0]
2576 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2577 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2578 assert_eq!(revoked_local_txn[0].input.len(), 1);
2579 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2580 assert_eq!(revoked_local_txn[1].input.len(), 1);
2581 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2582 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2583 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2585 //Revoke the old state
2586 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2589 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2590 check_added_monitors!(nodes[0], 1);
2591 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2592 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2593 check_added_monitors!(nodes[1], 1);
2594 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2595 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2596 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2598 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2599 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2601 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2602 check_spends!(node_txn[0], revoked_local_txn[0]);
2604 let mut witness_lens = BTreeSet::new();
2605 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2606 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2607 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2608 assert_eq!(witness_lens.len(), 3);
2609 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2610 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2611 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2613 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2614 // ANTI_REORG_DELAY confirmations.
2615 mine_transaction(&nodes[1], &node_txn[0]);
2616 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2617 expect_payment_failed!(nodes[1], payment_hash_2, false);
2619 get_announce_close_broadcast_events(&nodes, 0, 1);
2620 assert_eq!(nodes[0].node.list_channels().len(), 0);
2621 assert_eq!(nodes[1].node.list_channels().len(), 0);
2625 fn claim_htlc_outputs_single_tx() {
2626 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2627 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2628 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2631 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2633 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2635 // Rebalance the network to generate htlc in the two directions
2636 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2637 // 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
2638 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2639 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2640 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2642 // Get the will-be-revoked local txn from node[0]
2643 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2645 //Revoke the old state
2646 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2649 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2650 check_added_monitors!(nodes[0], 1);
2651 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2652 check_added_monitors!(nodes[1], 1);
2653 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2654 let mut events = nodes[0].node.get_and_clear_pending_events();
2655 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2656 match events.last().unwrap() {
2657 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2658 _ => panic!("Unexpected event"),
2661 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2662 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2664 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2666 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2667 assert_eq!(node_txn[0].input.len(), 1);
2668 check_spends!(node_txn[0], chan_1.3);
2669 assert_eq!(node_txn[1].input.len(), 1);
2670 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2671 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2672 check_spends!(node_txn[1], node_txn[0]);
2674 // Filter out any non justice transactions.
2675 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2676 assert!(node_txn.len() > 3);
2678 assert_eq!(node_txn[0].input.len(), 1);
2679 assert_eq!(node_txn[1].input.len(), 1);
2680 assert_eq!(node_txn[2].input.len(), 1);
2682 check_spends!(node_txn[0], revoked_local_txn[0]);
2683 check_spends!(node_txn[1], revoked_local_txn[0]);
2684 check_spends!(node_txn[2], revoked_local_txn[0]);
2686 let mut witness_lens = BTreeSet::new();
2687 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2688 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2689 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2690 assert_eq!(witness_lens.len(), 3);
2691 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2692 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2693 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2695 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2696 // ANTI_REORG_DELAY confirmations.
2697 mine_transaction(&nodes[1], &node_txn[0]);
2698 mine_transaction(&nodes[1], &node_txn[1]);
2699 mine_transaction(&nodes[1], &node_txn[2]);
2700 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2701 expect_payment_failed!(nodes[1], payment_hash_2, false);
2703 get_announce_close_broadcast_events(&nodes, 0, 1);
2704 assert_eq!(nodes[0].node.list_channels().len(), 0);
2705 assert_eq!(nodes[1].node.list_channels().len(), 0);
2709 fn test_htlc_on_chain_success() {
2710 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2711 // the preimage backward accordingly. So here we test that ChannelManager is
2712 // broadcasting the right event to other nodes in payment path.
2713 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2714 // A --------------------> B ----------------------> C (preimage)
2715 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2716 // commitment transaction was broadcast.
2717 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2719 // B should be able to claim via preimage if A then broadcasts its local tx.
2720 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2721 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2722 // PaymentSent event).
2724 let chanmon_cfgs = create_chanmon_cfgs(3);
2725 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2726 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2727 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2729 // Create some initial channels
2730 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2731 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2733 // Ensure all nodes are at the same height
2734 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2735 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2736 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2737 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2739 // Rebalance the network a bit by relaying one payment through all the channels...
2740 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2741 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2743 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2744 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2746 // Broadcast legit commitment tx from C on B's chain
2747 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2748 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2749 assert_eq!(commitment_tx.len(), 1);
2750 check_spends!(commitment_tx[0], chan_2.3);
2751 nodes[2].node.claim_funds(our_payment_preimage);
2752 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2753 nodes[2].node.claim_funds(our_payment_preimage_2);
2754 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2755 check_added_monitors!(nodes[2], 2);
2756 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2757 assert!(updates.update_add_htlcs.is_empty());
2758 assert!(updates.update_fail_htlcs.is_empty());
2759 assert!(updates.update_fail_malformed_htlcs.is_empty());
2760 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2762 mine_transaction(&nodes[2], &commitment_tx[0]);
2763 check_closed_broadcast!(nodes[2], true);
2764 check_added_monitors!(nodes[2], 1);
2765 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2766 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2767 assert_eq!(node_txn.len(), 2);
2768 check_spends!(node_txn[0], commitment_tx[0]);
2769 check_spends!(node_txn[1], commitment_tx[0]);
2770 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2771 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2772 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2773 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2774 assert_eq!(node_txn[0].lock_time.0, 0);
2775 assert_eq!(node_txn[1].lock_time.0, 0);
2777 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2778 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()]));
2779 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2781 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2782 assert_eq!(added_monitors.len(), 1);
2783 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2784 added_monitors.clear();
2786 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2787 assert_eq!(forwarded_events.len(), 3);
2788 match forwarded_events[0] {
2789 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2790 _ => panic!("Unexpected event"),
2792 let chan_id = Some(chan_1.2);
2793 match forwarded_events[1] {
2794 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2795 assert_eq!(fee_earned_msat, Some(1000));
2796 assert_eq!(prev_channel_id, chan_id);
2797 assert_eq!(claim_from_onchain_tx, true);
2798 assert_eq!(next_channel_id, Some(chan_2.2));
2799 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2803 match forwarded_events[2] {
2804 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2805 assert_eq!(fee_earned_msat, Some(1000));
2806 assert_eq!(prev_channel_id, chan_id);
2807 assert_eq!(claim_from_onchain_tx, true);
2808 assert_eq!(next_channel_id, Some(chan_2.2));
2809 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2813 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2815 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2816 assert_eq!(added_monitors.len(), 2);
2817 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2818 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2819 added_monitors.clear();
2821 assert_eq!(events.len(), 3);
2823 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2824 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2826 match nodes_2_event {
2827 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2828 _ => panic!("Unexpected event"),
2831 match nodes_0_event {
2832 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, .. } } => {
2833 assert!(update_add_htlcs.is_empty());
2834 assert!(update_fail_htlcs.is_empty());
2835 assert_eq!(update_fulfill_htlcs.len(), 1);
2836 assert!(update_fail_malformed_htlcs.is_empty());
2837 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2839 _ => panic!("Unexpected event"),
2842 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2844 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2845 _ => panic!("Unexpected event"),
2848 macro_rules! check_tx_local_broadcast {
2849 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2850 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2851 assert_eq!(node_txn.len(), 2);
2852 // Node[1]: 2 * HTLC-timeout tx
2853 // Node[0]: 2 * HTLC-timeout tx
2854 check_spends!(node_txn[0], $commitment_tx);
2855 check_spends!(node_txn[1], $commitment_tx);
2856 assert_ne!(node_txn[0].lock_time.0, 0);
2857 assert_ne!(node_txn[1].lock_time.0, 0);
2859 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2860 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2861 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2862 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2864 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2865 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2866 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2867 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2872 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2873 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2875 // Broadcast legit commitment tx from A on B's chain
2876 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2877 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2878 check_spends!(node_a_commitment_tx[0], chan_1.3);
2879 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2880 check_closed_broadcast!(nodes[1], true);
2881 check_added_monitors!(nodes[1], 1);
2882 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2883 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2884 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2885 let commitment_spend =
2886 if node_txn.len() == 1 {
2889 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2890 // FullBlockViaListen
2891 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2892 check_spends!(node_txn[1], commitment_tx[0]);
2893 check_spends!(node_txn[2], commitment_tx[0]);
2894 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2897 check_spends!(node_txn[0], commitment_tx[0]);
2898 check_spends!(node_txn[1], commitment_tx[0]);
2899 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2904 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2905 assert_eq!(commitment_spend.input.len(), 2);
2906 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2907 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2908 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2909 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2910 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2911 // we already checked the same situation with A.
2913 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2914 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2915 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2916 check_closed_broadcast!(nodes[0], true);
2917 check_added_monitors!(nodes[0], 1);
2918 let events = nodes[0].node.get_and_clear_pending_events();
2919 assert_eq!(events.len(), 5);
2920 let mut first_claimed = false;
2921 for event in events {
2923 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2924 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2925 assert!(!first_claimed);
2926 first_claimed = true;
2928 assert_eq!(payment_preimage, our_payment_preimage_2);
2929 assert_eq!(payment_hash, payment_hash_2);
2932 Event::PaymentPathSuccessful { .. } => {},
2933 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2934 _ => panic!("Unexpected event"),
2937 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2940 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2941 // Test that in case of a unilateral close onchain, we detect the state of output and
2942 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2943 // broadcasting the right event to other nodes in payment path.
2944 // A ------------------> B ----------------------> C (timeout)
2945 // B's commitment tx C's commitment tx
2947 // B's HTLC timeout tx B's timeout tx
2949 let chanmon_cfgs = create_chanmon_cfgs(3);
2950 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2951 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2952 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2953 *nodes[0].connect_style.borrow_mut() = connect_style;
2954 *nodes[1].connect_style.borrow_mut() = connect_style;
2955 *nodes[2].connect_style.borrow_mut() = connect_style;
2957 // Create some intial channels
2958 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2959 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2961 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2962 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2963 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2965 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2967 // Broadcast legit commitment tx from C on B's chain
2968 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2969 check_spends!(commitment_tx[0], chan_2.3);
2970 nodes[2].node.fail_htlc_backwards(&payment_hash);
2971 check_added_monitors!(nodes[2], 0);
2972 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2973 check_added_monitors!(nodes[2], 1);
2975 let events = nodes[2].node.get_and_clear_pending_msg_events();
2976 assert_eq!(events.len(), 1);
2978 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, .. } } => {
2979 assert!(update_add_htlcs.is_empty());
2980 assert!(!update_fail_htlcs.is_empty());
2981 assert!(update_fulfill_htlcs.is_empty());
2982 assert!(update_fail_malformed_htlcs.is_empty());
2983 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2985 _ => panic!("Unexpected event"),
2987 mine_transaction(&nodes[2], &commitment_tx[0]);
2988 check_closed_broadcast!(nodes[2], true);
2989 check_added_monitors!(nodes[2], 1);
2990 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2991 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2992 assert_eq!(node_txn.len(), 0);
2994 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2995 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2996 mine_transaction(&nodes[1], &commitment_tx[0]);
2997 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2998 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3000 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3001 if nodes[1].connect_style.borrow().skips_blocks() {
3002 assert_eq!(txn.len(), 1);
3004 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3006 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3007 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3011 mine_transaction(&nodes[1], &timeout_tx);
3012 check_added_monitors!(nodes[1], 1);
3013 check_closed_broadcast!(nodes[1], true);
3015 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3017 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 }]);
3018 check_added_monitors!(nodes[1], 1);
3019 let events = nodes[1].node.get_and_clear_pending_msg_events();
3020 assert_eq!(events.len(), 1);
3022 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, .. } } => {
3023 assert!(update_add_htlcs.is_empty());
3024 assert!(!update_fail_htlcs.is_empty());
3025 assert!(update_fulfill_htlcs.is_empty());
3026 assert!(update_fail_malformed_htlcs.is_empty());
3027 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3029 _ => panic!("Unexpected event"),
3032 // Broadcast legit commitment tx from B on A's chain
3033 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3034 check_spends!(commitment_tx[0], chan_1.3);
3036 mine_transaction(&nodes[0], &commitment_tx[0]);
3037 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3039 check_closed_broadcast!(nodes[0], true);
3040 check_added_monitors!(nodes[0], 1);
3041 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3042 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3043 assert_eq!(node_txn.len(), 1);
3044 check_spends!(node_txn[0], commitment_tx[0]);
3045 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3049 fn test_htlc_on_chain_timeout() {
3050 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3051 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3052 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3056 fn test_simple_commitment_revoked_fail_backward() {
3057 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3058 // and fail backward accordingly.
3060 let chanmon_cfgs = create_chanmon_cfgs(3);
3061 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3062 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3063 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3065 // Create some initial channels
3066 create_announced_chan_between_nodes(&nodes, 0, 1);
3067 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3069 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3070 // Get the will-be-revoked local txn from nodes[2]
3071 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3072 // Revoke the old state
3073 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3075 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3077 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3078 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3079 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3080 check_added_monitors!(nodes[1], 1);
3081 check_closed_broadcast!(nodes[1], true);
3083 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 }]);
3084 check_added_monitors!(nodes[1], 1);
3085 let events = nodes[1].node.get_and_clear_pending_msg_events();
3086 assert_eq!(events.len(), 1);
3088 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, .. } } => {
3089 assert!(update_add_htlcs.is_empty());
3090 assert_eq!(update_fail_htlcs.len(), 1);
3091 assert!(update_fulfill_htlcs.is_empty());
3092 assert!(update_fail_malformed_htlcs.is_empty());
3093 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3095 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3096 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3097 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3099 _ => panic!("Unexpected event"),
3103 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3104 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3105 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3106 // commitment transaction anymore.
3107 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3108 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3109 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3110 // technically disallowed and we should probably handle it reasonably.
3111 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3112 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3114 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3115 // commitment_signed (implying it will be in the latest remote commitment transaction).
3116 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3117 // and once they revoke the previous commitment transaction (allowing us to send a new
3118 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3119 let chanmon_cfgs = create_chanmon_cfgs(3);
3120 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3121 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3122 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3124 // Create some initial channels
3125 create_announced_chan_between_nodes(&nodes, 0, 1);
3126 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3128 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 });
3129 // Get the will-be-revoked local txn from nodes[2]
3130 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3131 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3132 // Revoke the old state
3133 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3135 let value = if use_dust {
3136 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3137 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3138 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3139 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3142 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3143 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3144 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3146 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3147 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3148 check_added_monitors!(nodes[2], 1);
3149 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3150 assert!(updates.update_add_htlcs.is_empty());
3151 assert!(updates.update_fulfill_htlcs.is_empty());
3152 assert!(updates.update_fail_malformed_htlcs.is_empty());
3153 assert_eq!(updates.update_fail_htlcs.len(), 1);
3154 assert!(updates.update_fee.is_none());
3155 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3156 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3157 // Drop the last RAA from 3 -> 2
3159 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3160 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3161 check_added_monitors!(nodes[2], 1);
3162 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3163 assert!(updates.update_add_htlcs.is_empty());
3164 assert!(updates.update_fulfill_htlcs.is_empty());
3165 assert!(updates.update_fail_malformed_htlcs.is_empty());
3166 assert_eq!(updates.update_fail_htlcs.len(), 1);
3167 assert!(updates.update_fee.is_none());
3168 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3169 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3170 check_added_monitors!(nodes[1], 1);
3171 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3172 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3173 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3174 check_added_monitors!(nodes[2], 1);
3176 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3177 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3178 check_added_monitors!(nodes[2], 1);
3179 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3180 assert!(updates.update_add_htlcs.is_empty());
3181 assert!(updates.update_fulfill_htlcs.is_empty());
3182 assert!(updates.update_fail_malformed_htlcs.is_empty());
3183 assert_eq!(updates.update_fail_htlcs.len(), 1);
3184 assert!(updates.update_fee.is_none());
3185 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3186 // At this point first_payment_hash has dropped out of the latest two commitment
3187 // transactions that nodes[1] is tracking...
3188 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3189 check_added_monitors!(nodes[1], 1);
3190 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3191 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3192 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3193 check_added_monitors!(nodes[2], 1);
3195 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3196 // on nodes[2]'s RAA.
3197 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3198 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3199 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3200 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3201 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3202 check_added_monitors!(nodes[1], 0);
3205 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3206 // One monitor for the new revocation preimage, no second on as we won't generate a new
3207 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3208 check_added_monitors!(nodes[1], 1);
3209 let events = nodes[1].node.get_and_clear_pending_events();
3210 assert_eq!(events.len(), 2);
3212 Event::PendingHTLCsForwardable { .. } => { },
3213 _ => panic!("Unexpected event"),
3216 Event::HTLCHandlingFailed { .. } => { },
3217 _ => panic!("Unexpected event"),
3219 // Deliberately don't process the pending fail-back so they all fail back at once after
3220 // block connection just like the !deliver_bs_raa case
3223 let mut failed_htlcs = HashSet::new();
3224 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3226 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3227 check_added_monitors!(nodes[1], 1);
3228 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3230 let events = nodes[1].node.get_and_clear_pending_events();
3231 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3233 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3234 _ => panic!("Unexepected event"),
3237 Event::PaymentPathFailed { ref payment_hash, .. } => {
3238 assert_eq!(*payment_hash, fourth_payment_hash);
3240 _ => panic!("Unexpected event"),
3243 Event::PaymentFailed { ref payment_hash, .. } => {
3244 assert_eq!(*payment_hash, fourth_payment_hash);
3246 _ => panic!("Unexpected event"),
3249 nodes[1].node.process_pending_htlc_forwards();
3250 check_added_monitors!(nodes[1], 1);
3252 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3253 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3256 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3257 match nodes_2_event {
3258 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, .. } } => {
3259 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3260 assert_eq!(update_add_htlcs.len(), 1);
3261 assert!(update_fulfill_htlcs.is_empty());
3262 assert!(update_fail_htlcs.is_empty());
3263 assert!(update_fail_malformed_htlcs.is_empty());
3265 _ => panic!("Unexpected event"),
3269 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3270 match nodes_2_event {
3271 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3272 assert_eq!(channel_id, chan_2.2);
3273 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3275 _ => panic!("Unexpected event"),
3278 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3279 match nodes_0_event {
3280 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, .. } } => {
3281 assert!(update_add_htlcs.is_empty());
3282 assert_eq!(update_fail_htlcs.len(), 3);
3283 assert!(update_fulfill_htlcs.is_empty());
3284 assert!(update_fail_malformed_htlcs.is_empty());
3285 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3287 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3288 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3289 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3291 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3293 let events = nodes[0].node.get_and_clear_pending_events();
3294 assert_eq!(events.len(), 6);
3296 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3297 assert!(failed_htlcs.insert(payment_hash.0));
3298 // If we delivered B's RAA we got an unknown preimage error, not something
3299 // that we should update our routing table for.
3300 if !deliver_bs_raa {
3301 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3304 _ => panic!("Unexpected event"),
3307 Event::PaymentFailed { ref payment_hash, .. } => {
3308 assert_eq!(*payment_hash, first_payment_hash);
3310 _ => panic!("Unexpected event"),
3313 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3314 assert!(failed_htlcs.insert(payment_hash.0));
3316 _ => panic!("Unexpected event"),
3319 Event::PaymentFailed { ref payment_hash, .. } => {
3320 assert_eq!(*payment_hash, second_payment_hash);
3322 _ => panic!("Unexpected event"),
3325 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3326 assert!(failed_htlcs.insert(payment_hash.0));
3328 _ => panic!("Unexpected event"),
3331 Event::PaymentFailed { ref payment_hash, .. } => {
3332 assert_eq!(*payment_hash, third_payment_hash);
3334 _ => panic!("Unexpected event"),
3337 _ => panic!("Unexpected event"),
3340 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3342 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3343 _ => panic!("Unexpected event"),
3346 assert!(failed_htlcs.contains(&first_payment_hash.0));
3347 assert!(failed_htlcs.contains(&second_payment_hash.0));
3348 assert!(failed_htlcs.contains(&third_payment_hash.0));
3352 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3353 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3354 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3355 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3356 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3360 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3361 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3362 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3363 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3364 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3368 fn fail_backward_pending_htlc_upon_channel_failure() {
3369 let chanmon_cfgs = create_chanmon_cfgs(2);
3370 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3371 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3372 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3373 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3375 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3377 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3378 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3379 PaymentId(payment_hash.0)).unwrap();
3380 check_added_monitors!(nodes[0], 1);
3382 let payment_event = {
3383 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3384 assert_eq!(events.len(), 1);
3385 SendEvent::from_event(events.remove(0))
3387 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3388 assert_eq!(payment_event.msgs.len(), 1);
3391 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3392 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3394 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3395 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3396 check_added_monitors!(nodes[0], 0);
3398 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3401 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3403 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3405 let secp_ctx = Secp256k1::new();
3406 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3407 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3408 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3409 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3410 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3411 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3413 // Send a 0-msat update_add_htlc to fail the channel.
3414 let update_add_htlc = msgs::UpdateAddHTLC {
3420 onion_routing_packet,
3422 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3424 let events = nodes[0].node.get_and_clear_pending_events();
3425 assert_eq!(events.len(), 3);
3426 // Check that Alice fails backward the pending HTLC from the second payment.
3428 Event::PaymentPathFailed { payment_hash, .. } => {
3429 assert_eq!(payment_hash, failed_payment_hash);
3431 _ => panic!("Unexpected event"),
3434 Event::PaymentFailed { payment_hash, .. } => {
3435 assert_eq!(payment_hash, failed_payment_hash);
3437 _ => panic!("Unexpected event"),
3440 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3441 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3443 _ => panic!("Unexpected event {:?}", events[1]),
3445 check_closed_broadcast!(nodes[0], true);
3446 check_added_monitors!(nodes[0], 1);
3450 fn test_htlc_ignore_latest_remote_commitment() {
3451 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3452 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3453 let chanmon_cfgs = create_chanmon_cfgs(2);
3454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3455 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3456 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3457 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3458 // We rely on the ability to connect a block redundantly, which isn't allowed via
3459 // `chain::Listen`, so we never run the test if we randomly get assigned that
3463 create_announced_chan_between_nodes(&nodes, 0, 1);
3465 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3466 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3467 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3468 check_closed_broadcast!(nodes[0], true);
3469 check_added_monitors!(nodes[0], 1);
3470 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3472 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3473 assert_eq!(node_txn.len(), 3);
3474 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3476 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3477 connect_block(&nodes[1], &block);
3478 check_closed_broadcast!(nodes[1], true);
3479 check_added_monitors!(nodes[1], 1);
3480 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3482 // Duplicate the connect_block call since this may happen due to other listeners
3483 // registering new transactions
3484 connect_block(&nodes[1], &block);
3488 fn test_force_close_fail_back() {
3489 // Check which HTLCs are failed-backwards on channel force-closure
3490 let chanmon_cfgs = create_chanmon_cfgs(3);
3491 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3492 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3493 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3494 create_announced_chan_between_nodes(&nodes, 0, 1);
3495 create_announced_chan_between_nodes(&nodes, 1, 2);
3497 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3499 let mut payment_event = {
3500 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3501 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3502 check_added_monitors!(nodes[0], 1);
3504 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3505 assert_eq!(events.len(), 1);
3506 SendEvent::from_event(events.remove(0))
3509 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3510 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3512 expect_pending_htlcs_forwardable!(nodes[1]);
3514 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3515 assert_eq!(events_2.len(), 1);
3516 payment_event = SendEvent::from_event(events_2.remove(0));
3517 assert_eq!(payment_event.msgs.len(), 1);
3519 check_added_monitors!(nodes[1], 1);
3520 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3521 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3522 check_added_monitors!(nodes[2], 1);
3523 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3525 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3526 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3527 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3529 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3530 check_closed_broadcast!(nodes[2], true);
3531 check_added_monitors!(nodes[2], 1);
3532 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3534 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3535 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3536 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3537 // back to nodes[1] upon timeout otherwise.
3538 assert_eq!(node_txn.len(), 1);
3542 mine_transaction(&nodes[1], &tx);
3544 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3545 check_closed_broadcast!(nodes[1], true);
3546 check_added_monitors!(nodes[1], 1);
3547 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3549 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3551 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3552 .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);
3554 mine_transaction(&nodes[2], &tx);
3555 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3556 assert_eq!(node_txn.len(), 1);
3557 assert_eq!(node_txn[0].input.len(), 1);
3558 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3559 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3560 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3562 check_spends!(node_txn[0], tx);
3566 fn test_dup_events_on_peer_disconnect() {
3567 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3568 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3569 // as we used to generate the event immediately upon receipt of the payment preimage in the
3570 // update_fulfill_htlc message.
3572 let chanmon_cfgs = create_chanmon_cfgs(2);
3573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3575 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3576 create_announced_chan_between_nodes(&nodes, 0, 1);
3578 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3580 nodes[1].node.claim_funds(payment_preimage);
3581 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3582 check_added_monitors!(nodes[1], 1);
3583 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3584 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3585 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3587 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3588 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3590 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3591 expect_payment_path_successful!(nodes[0]);
3595 fn test_peer_disconnected_before_funding_broadcasted() {
3596 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3597 // before the funding transaction has been broadcasted.
3598 let chanmon_cfgs = create_chanmon_cfgs(2);
3599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3601 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3603 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3604 // broadcasted, even though it's created by `nodes[0]`.
3605 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();
3606 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3607 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3608 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3609 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3611 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3612 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3614 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3616 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3617 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3619 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3620 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3623 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3626 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3627 // disconnected before the funding transaction was broadcasted.
3628 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3629 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3631 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3632 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3636 fn test_simple_peer_disconnect() {
3637 // Test that we can reconnect when there are no lost messages
3638 let chanmon_cfgs = create_chanmon_cfgs(3);
3639 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3640 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3641 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3642 create_announced_chan_between_nodes(&nodes, 0, 1);
3643 create_announced_chan_between_nodes(&nodes, 1, 2);
3645 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3646 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3647 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3649 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3650 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3651 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3652 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3654 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3655 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3656 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3658 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3659 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3660 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3661 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3663 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3664 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3666 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3667 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3669 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3671 let events = nodes[0].node.get_and_clear_pending_events();
3672 assert_eq!(events.len(), 4);
3674 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3675 assert_eq!(payment_preimage, payment_preimage_3);
3676 assert_eq!(payment_hash, payment_hash_3);
3678 _ => panic!("Unexpected event"),
3681 Event::PaymentPathSuccessful { .. } => {},
3682 _ => panic!("Unexpected event"),
3685 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3686 assert_eq!(payment_hash, payment_hash_5);
3687 assert!(payment_failed_permanently);
3689 _ => panic!("Unexpected event"),
3692 Event::PaymentFailed { payment_hash, .. } => {
3693 assert_eq!(payment_hash, payment_hash_5);
3695 _ => panic!("Unexpected event"),
3699 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3700 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3703 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3704 // Test that we can reconnect when in-flight HTLC updates get dropped
3705 let chanmon_cfgs = create_chanmon_cfgs(2);
3706 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3707 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3708 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3710 let mut as_channel_ready = None;
3711 let channel_id = if messages_delivered == 0 {
3712 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3713 as_channel_ready = Some(channel_ready);
3714 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3715 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3716 // it before the channel_reestablish message.
3719 create_announced_chan_between_nodes(&nodes, 0, 1).2
3722 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3724 let payment_event = {
3725 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3726 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3727 check_added_monitors!(nodes[0], 1);
3729 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3730 assert_eq!(events.len(), 1);
3731 SendEvent::from_event(events.remove(0))
3733 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3735 if messages_delivered < 2 {
3736 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3738 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3739 if messages_delivered >= 3 {
3740 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3741 check_added_monitors!(nodes[1], 1);
3742 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3744 if messages_delivered >= 4 {
3745 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3746 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3747 check_added_monitors!(nodes[0], 1);
3749 if messages_delivered >= 5 {
3750 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3751 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3752 // No commitment_signed so get_event_msg's assert(len == 1) passes
3753 check_added_monitors!(nodes[0], 1);
3755 if messages_delivered >= 6 {
3756 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3757 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3758 check_added_monitors!(nodes[1], 1);
3765 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3766 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3767 if messages_delivered < 3 {
3768 if simulate_broken_lnd {
3769 // lnd has a long-standing bug where they send a channel_ready prior to a
3770 // channel_reestablish if you reconnect prior to channel_ready time.
3772 // Here we simulate that behavior, delivering a channel_ready immediately on
3773 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3774 // in `reconnect_nodes` but we currently don't fail based on that.
3776 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3777 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3779 // Even if the channel_ready messages get exchanged, as long as nothing further was
3780 // received on either side, both sides will need to resend them.
3781 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3782 } else if messages_delivered == 3 {
3783 // nodes[0] still wants its RAA + commitment_signed
3784 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3785 } else if messages_delivered == 4 {
3786 // nodes[0] still wants its commitment_signed
3787 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3788 } else if messages_delivered == 5 {
3789 // nodes[1] still wants its final RAA
3790 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3791 } else if messages_delivered == 6 {
3792 // Everything was delivered...
3793 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3796 let events_1 = nodes[1].node.get_and_clear_pending_events();
3797 if messages_delivered == 0 {
3798 assert_eq!(events_1.len(), 2);
3800 Event::ChannelReady { .. } => { },
3801 _ => panic!("Unexpected event"),
3804 Event::PendingHTLCsForwardable { .. } => { },
3805 _ => panic!("Unexpected event"),
3808 assert_eq!(events_1.len(), 1);
3810 Event::PendingHTLCsForwardable { .. } => { },
3811 _ => panic!("Unexpected event"),
3815 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3816 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3817 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3819 nodes[1].node.process_pending_htlc_forwards();
3821 let events_2 = nodes[1].node.get_and_clear_pending_events();
3822 assert_eq!(events_2.len(), 1);
3824 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3825 assert_eq!(payment_hash_1, *payment_hash);
3826 assert_eq!(amount_msat, 1_000_000);
3827 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3828 assert_eq!(via_channel_id, Some(channel_id));
3830 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3831 assert!(payment_preimage.is_none());
3832 assert_eq!(payment_secret_1, *payment_secret);
3834 _ => panic!("expected PaymentPurpose::InvoicePayment")
3837 _ => panic!("Unexpected event"),
3840 nodes[1].node.claim_funds(payment_preimage_1);
3841 check_added_monitors!(nodes[1], 1);
3842 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3844 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3845 assert_eq!(events_3.len(), 1);
3846 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3847 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3848 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3849 assert!(updates.update_add_htlcs.is_empty());
3850 assert!(updates.update_fail_htlcs.is_empty());
3851 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3852 assert!(updates.update_fail_malformed_htlcs.is_empty());
3853 assert!(updates.update_fee.is_none());
3854 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3856 _ => panic!("Unexpected event"),
3859 if messages_delivered >= 1 {
3860 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3862 let events_4 = nodes[0].node.get_and_clear_pending_events();
3863 assert_eq!(events_4.len(), 1);
3865 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3866 assert_eq!(payment_preimage_1, *payment_preimage);
3867 assert_eq!(payment_hash_1, *payment_hash);
3869 _ => panic!("Unexpected event"),
3872 if messages_delivered >= 2 {
3873 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3874 check_added_monitors!(nodes[0], 1);
3875 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3877 if messages_delivered >= 3 {
3878 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3879 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3880 check_added_monitors!(nodes[1], 1);
3882 if messages_delivered >= 4 {
3883 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3884 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3885 // No commitment_signed so get_event_msg's assert(len == 1) passes
3886 check_added_monitors!(nodes[1], 1);
3888 if messages_delivered >= 5 {
3889 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3890 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3891 check_added_monitors!(nodes[0], 1);
3898 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3899 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3900 if messages_delivered < 2 {
3901 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3902 if messages_delivered < 1 {
3903 expect_payment_sent!(nodes[0], payment_preimage_1);
3905 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3907 } else if messages_delivered == 2 {
3908 // nodes[0] still wants its RAA + commitment_signed
3909 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3910 } else if messages_delivered == 3 {
3911 // nodes[0] still wants its commitment_signed
3912 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3913 } else if messages_delivered == 4 {
3914 // nodes[1] still wants its final RAA
3915 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3916 } else if messages_delivered == 5 {
3917 // Everything was delivered...
3918 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3921 if messages_delivered == 1 || messages_delivered == 2 {
3922 expect_payment_path_successful!(nodes[0]);
3924 if messages_delivered <= 5 {
3925 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3926 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3928 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3930 if messages_delivered > 2 {
3931 expect_payment_path_successful!(nodes[0]);
3934 // Channel should still work fine...
3935 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3936 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3937 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3941 fn test_drop_messages_peer_disconnect_a() {
3942 do_test_drop_messages_peer_disconnect(0, true);
3943 do_test_drop_messages_peer_disconnect(0, false);
3944 do_test_drop_messages_peer_disconnect(1, false);
3945 do_test_drop_messages_peer_disconnect(2, false);
3949 fn test_drop_messages_peer_disconnect_b() {
3950 do_test_drop_messages_peer_disconnect(3, false);
3951 do_test_drop_messages_peer_disconnect(4, false);
3952 do_test_drop_messages_peer_disconnect(5, false);
3953 do_test_drop_messages_peer_disconnect(6, false);
3957 fn test_channel_ready_without_best_block_updated() {
3958 // Previously, if we were offline when a funding transaction was locked in, and then we came
3959 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3960 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3961 // channel_ready immediately instead.
3962 let chanmon_cfgs = create_chanmon_cfgs(2);
3963 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3964 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3965 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3966 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3968 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3970 let conf_height = nodes[0].best_block_info().1 + 1;
3971 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3972 let block_txn = [funding_tx];
3973 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3974 let conf_block_header = nodes[0].get_block_header(conf_height);
3975 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3977 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3978 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3979 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3983 fn test_drop_messages_peer_disconnect_dual_htlc() {
3984 // Test that we can handle reconnecting when both sides of a channel have pending
3985 // commitment_updates when we disconnect.
3986 let chanmon_cfgs = create_chanmon_cfgs(2);
3987 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3988 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3989 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3990 create_announced_chan_between_nodes(&nodes, 0, 1);
3992 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3994 // Now try to send a second payment which will fail to send
3995 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3996 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3997 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3998 check_added_monitors!(nodes[0], 1);
4000 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4001 assert_eq!(events_1.len(), 1);
4003 MessageSendEvent::UpdateHTLCs { .. } => {},
4004 _ => panic!("Unexpected event"),
4007 nodes[1].node.claim_funds(payment_preimage_1);
4008 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4009 check_added_monitors!(nodes[1], 1);
4011 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4012 assert_eq!(events_2.len(), 1);
4014 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 } } => {
4015 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4016 assert!(update_add_htlcs.is_empty());
4017 assert_eq!(update_fulfill_htlcs.len(), 1);
4018 assert!(update_fail_htlcs.is_empty());
4019 assert!(update_fail_malformed_htlcs.is_empty());
4020 assert!(update_fee.is_none());
4022 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4023 let events_3 = nodes[0].node.get_and_clear_pending_events();
4024 assert_eq!(events_3.len(), 1);
4026 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4027 assert_eq!(*payment_preimage, payment_preimage_1);
4028 assert_eq!(*payment_hash, payment_hash_1);
4030 _ => panic!("Unexpected event"),
4033 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4034 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4035 // No commitment_signed so get_event_msg's assert(len == 1) passes
4036 check_added_monitors!(nodes[0], 1);
4038 _ => panic!("Unexpected event"),
4041 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4042 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4044 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();
4045 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4046 assert_eq!(reestablish_1.len(), 1);
4047 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();
4048 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4049 assert_eq!(reestablish_2.len(), 1);
4051 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4052 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4053 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4054 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4056 assert!(as_resp.0.is_none());
4057 assert!(bs_resp.0.is_none());
4059 assert!(bs_resp.1.is_none());
4060 assert!(bs_resp.2.is_none());
4062 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4064 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4065 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4066 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4067 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4068 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4069 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4070 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4071 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4072 // No commitment_signed so get_event_msg's assert(len == 1) passes
4073 check_added_monitors!(nodes[1], 1);
4075 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4076 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4077 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4078 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4079 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4080 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4081 assert!(bs_second_commitment_signed.update_fee.is_none());
4082 check_added_monitors!(nodes[1], 1);
4084 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4085 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4086 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4087 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4088 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4089 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4090 assert!(as_commitment_signed.update_fee.is_none());
4091 check_added_monitors!(nodes[0], 1);
4093 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4094 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4095 // No commitment_signed so get_event_msg's assert(len == 1) passes
4096 check_added_monitors!(nodes[0], 1);
4098 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4099 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4100 // No commitment_signed so get_event_msg's assert(len == 1) passes
4101 check_added_monitors!(nodes[1], 1);
4103 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4104 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4105 check_added_monitors!(nodes[1], 1);
4107 expect_pending_htlcs_forwardable!(nodes[1]);
4109 let events_5 = nodes[1].node.get_and_clear_pending_events();
4110 assert_eq!(events_5.len(), 1);
4112 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4113 assert_eq!(payment_hash_2, *payment_hash);
4115 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4116 assert!(payment_preimage.is_none());
4117 assert_eq!(payment_secret_2, *payment_secret);
4119 _ => panic!("expected PaymentPurpose::InvoicePayment")
4122 _ => panic!("Unexpected event"),
4125 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4126 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4127 check_added_monitors!(nodes[0], 1);
4129 expect_payment_path_successful!(nodes[0]);
4130 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4133 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4134 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4135 // to avoid our counterparty failing the channel.
4136 let chanmon_cfgs = create_chanmon_cfgs(2);
4137 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4138 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4139 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4141 create_announced_chan_between_nodes(&nodes, 0, 1);
4143 let our_payment_hash = if send_partial_mpp {
4144 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4145 // Use the utility function send_payment_along_path to send the payment with MPP data which
4146 // indicates there are more HTLCs coming.
4147 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4148 let payment_id = PaymentId([42; 32]);
4149 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4150 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4151 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4152 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4153 &None, session_privs[0]).unwrap();
4154 check_added_monitors!(nodes[0], 1);
4155 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4156 assert_eq!(events.len(), 1);
4157 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4158 // hop should *not* yet generate any PaymentClaimable event(s).
4159 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4162 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4165 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4166 connect_block(&nodes[0], &block);
4167 connect_block(&nodes[1], &block);
4168 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4169 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4170 block.header.prev_blockhash = block.block_hash();
4171 connect_block(&nodes[0], &block);
4172 connect_block(&nodes[1], &block);
4175 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4177 check_added_monitors!(nodes[1], 1);
4178 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4179 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4180 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4181 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4182 assert!(htlc_timeout_updates.update_fee.is_none());
4184 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4185 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4186 // 100_000 msat as u64, followed by the height at which we failed back above
4187 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4188 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4189 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4193 fn test_htlc_timeout() {
4194 do_test_htlc_timeout(true);
4195 do_test_htlc_timeout(false);
4198 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4199 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4200 let chanmon_cfgs = create_chanmon_cfgs(3);
4201 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4202 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4203 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4204 create_announced_chan_between_nodes(&nodes, 0, 1);
4205 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4207 // Make sure all nodes are at the same starting height
4208 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4209 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4210 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4212 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4213 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4214 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4215 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4216 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4217 check_added_monitors!(nodes[1], 1);
4219 // Now attempt to route a second payment, which should be placed in the holding cell
4220 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4221 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4222 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4223 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4225 check_added_monitors!(nodes[0], 1);
4226 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4227 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4228 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4229 expect_pending_htlcs_forwardable!(nodes[1]);
4231 check_added_monitors!(nodes[1], 0);
4233 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4234 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4235 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4236 connect_blocks(&nodes[1], 1);
4239 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4240 check_added_monitors!(nodes[1], 1);
4241 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4242 assert_eq!(fail_commit.len(), 1);
4243 match fail_commit[0] {
4244 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4245 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4246 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4248 _ => unreachable!(),
4250 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4252 expect_payment_failed!(nodes[1], second_payment_hash, false);
4257 fn test_holding_cell_htlc_add_timeouts() {
4258 do_test_holding_cell_htlc_add_timeouts(false);
4259 do_test_holding_cell_htlc_add_timeouts(true);
4262 macro_rules! check_spendable_outputs {
4263 ($node: expr, $keysinterface: expr) => {
4265 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4266 let mut txn = Vec::new();
4267 let mut all_outputs = Vec::new();
4268 let secp_ctx = Secp256k1::new();
4269 for event in events.drain(..) {
4271 Event::SpendableOutputs { mut outputs } => {
4272 for outp in outputs.drain(..) {
4273 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx).unwrap());
4274 all_outputs.push(outp);
4277 _ => panic!("Unexpected event"),
4280 if all_outputs.len() > 1 {
4281 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx) {
4291 fn test_claim_sizeable_push_msat() {
4292 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4293 let chanmon_cfgs = create_chanmon_cfgs(2);
4294 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4295 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4296 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4298 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4299 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4300 check_closed_broadcast!(nodes[1], true);
4301 check_added_monitors!(nodes[1], 1);
4302 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4303 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4304 assert_eq!(node_txn.len(), 1);
4305 check_spends!(node_txn[0], chan.3);
4306 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4308 mine_transaction(&nodes[1], &node_txn[0]);
4309 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4311 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4312 assert_eq!(spend_txn.len(), 1);
4313 assert_eq!(spend_txn[0].input.len(), 1);
4314 check_spends!(spend_txn[0], node_txn[0]);
4315 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4319 fn test_claim_on_remote_sizeable_push_msat() {
4320 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4321 // to_remote output is encumbered by a P2WPKH
4322 let chanmon_cfgs = create_chanmon_cfgs(2);
4323 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4324 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4325 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4327 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4328 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4329 check_closed_broadcast!(nodes[0], true);
4330 check_added_monitors!(nodes[0], 1);
4331 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4333 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4334 assert_eq!(node_txn.len(), 1);
4335 check_spends!(node_txn[0], chan.3);
4336 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4338 mine_transaction(&nodes[1], &node_txn[0]);
4339 check_closed_broadcast!(nodes[1], true);
4340 check_added_monitors!(nodes[1], 1);
4341 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4342 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4344 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4345 assert_eq!(spend_txn.len(), 1);
4346 check_spends!(spend_txn[0], node_txn[0]);
4350 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4351 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4352 // to_remote output is encumbered by a P2WPKH
4354 let chanmon_cfgs = create_chanmon_cfgs(2);
4355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4357 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4359 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4360 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4361 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4362 assert_eq!(revoked_local_txn[0].input.len(), 1);
4363 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4365 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4366 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4367 check_closed_broadcast!(nodes[1], true);
4368 check_added_monitors!(nodes[1], 1);
4369 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4371 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4372 mine_transaction(&nodes[1], &node_txn[0]);
4373 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4375 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4376 assert_eq!(spend_txn.len(), 3);
4377 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4378 check_spends!(spend_txn[1], node_txn[0]);
4379 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4383 fn test_static_spendable_outputs_preimage_tx() {
4384 let chanmon_cfgs = create_chanmon_cfgs(2);
4385 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4386 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4387 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4389 // Create some initial channels
4390 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4392 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4394 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4395 assert_eq!(commitment_tx[0].input.len(), 1);
4396 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4398 // Settle A's commitment tx on B's chain
4399 nodes[1].node.claim_funds(payment_preimage);
4400 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4401 check_added_monitors!(nodes[1], 1);
4402 mine_transaction(&nodes[1], &commitment_tx[0]);
4403 check_added_monitors!(nodes[1], 1);
4404 let events = nodes[1].node.get_and_clear_pending_msg_events();
4406 MessageSendEvent::UpdateHTLCs { .. } => {},
4407 _ => panic!("Unexpected event"),
4410 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4411 _ => panic!("Unexepected event"),
4414 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4415 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4416 assert_eq!(node_txn.len(), 1);
4417 check_spends!(node_txn[0], commitment_tx[0]);
4418 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4420 mine_transaction(&nodes[1], &node_txn[0]);
4421 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4422 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4424 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4425 assert_eq!(spend_txn.len(), 1);
4426 check_spends!(spend_txn[0], node_txn[0]);
4430 fn test_static_spendable_outputs_timeout_tx() {
4431 let chanmon_cfgs = create_chanmon_cfgs(2);
4432 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4433 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4434 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4436 // Create some initial channels
4437 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4439 // Rebalance the network a bit by relaying one payment through all the channels ...
4440 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4442 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4444 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4445 assert_eq!(commitment_tx[0].input.len(), 1);
4446 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4448 // Settle A's commitment tx on B' chain
4449 mine_transaction(&nodes[1], &commitment_tx[0]);
4450 check_added_monitors!(nodes[1], 1);
4451 let events = nodes[1].node.get_and_clear_pending_msg_events();
4453 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4454 _ => panic!("Unexpected event"),
4456 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4458 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4459 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4460 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4461 check_spends!(node_txn[0], commitment_tx[0].clone());
4462 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4464 mine_transaction(&nodes[1], &node_txn[0]);
4465 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4466 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4467 expect_payment_failed!(nodes[1], our_payment_hash, false);
4469 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4470 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4471 check_spends!(spend_txn[0], commitment_tx[0]);
4472 check_spends!(spend_txn[1], node_txn[0]);
4473 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4477 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4478 let chanmon_cfgs = create_chanmon_cfgs(2);
4479 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4480 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4481 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4483 // Create some initial channels
4484 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4486 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4487 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4488 assert_eq!(revoked_local_txn[0].input.len(), 1);
4489 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4491 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4493 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4494 check_closed_broadcast!(nodes[1], true);
4495 check_added_monitors!(nodes[1], 1);
4496 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4498 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4499 assert_eq!(node_txn.len(), 1);
4500 assert_eq!(node_txn[0].input.len(), 2);
4501 check_spends!(node_txn[0], revoked_local_txn[0]);
4503 mine_transaction(&nodes[1], &node_txn[0]);
4504 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4506 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4507 assert_eq!(spend_txn.len(), 1);
4508 check_spends!(spend_txn[0], node_txn[0]);
4512 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4513 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4514 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4519 // Create some initial channels
4520 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4522 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4523 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4524 assert_eq!(revoked_local_txn[0].input.len(), 1);
4525 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4527 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4529 // A will generate HTLC-Timeout from revoked commitment tx
4530 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4531 check_closed_broadcast!(nodes[0], true);
4532 check_added_monitors!(nodes[0], 1);
4533 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4534 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4536 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4537 assert_eq!(revoked_htlc_txn.len(), 1);
4538 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4539 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4540 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4541 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4543 // B will generate justice tx from A's revoked commitment/HTLC tx
4544 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4545 check_closed_broadcast!(nodes[1], true);
4546 check_added_monitors!(nodes[1], 1);
4547 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4549 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4550 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4551 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4552 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4553 // transactions next...
4554 assert_eq!(node_txn[0].input.len(), 3);
4555 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4557 assert_eq!(node_txn[1].input.len(), 2);
4558 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4559 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4560 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4562 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4563 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4566 mine_transaction(&nodes[1], &node_txn[1]);
4567 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4569 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4570 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4571 assert_eq!(spend_txn.len(), 1);
4572 assert_eq!(spend_txn[0].input.len(), 1);
4573 check_spends!(spend_txn[0], node_txn[1]);
4577 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4578 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4579 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4582 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4584 // Create some initial channels
4585 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4587 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4588 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4589 assert_eq!(revoked_local_txn[0].input.len(), 1);
4590 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4592 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4593 assert_eq!(revoked_local_txn[0].output.len(), 2);
4595 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4597 // B will generate HTLC-Success from revoked commitment tx
4598 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4599 check_closed_broadcast!(nodes[1], true);
4600 check_added_monitors!(nodes[1], 1);
4601 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4602 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4604 assert_eq!(revoked_htlc_txn.len(), 1);
4605 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4606 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4607 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4609 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4610 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4611 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4613 // A will generate justice tx from B's revoked commitment/HTLC tx
4614 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4615 check_closed_broadcast!(nodes[0], true);
4616 check_added_monitors!(nodes[0], 1);
4617 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4619 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4620 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4622 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4623 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4624 // transactions next...
4625 assert_eq!(node_txn[0].input.len(), 2);
4626 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4627 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4628 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4630 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4631 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4634 assert_eq!(node_txn[1].input.len(), 1);
4635 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4637 mine_transaction(&nodes[0], &node_txn[1]);
4638 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4640 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4641 // didn't try to generate any new transactions.
4643 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4644 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4645 assert_eq!(spend_txn.len(), 3);
4646 assert_eq!(spend_txn[0].input.len(), 1);
4647 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4648 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4649 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4650 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4654 fn test_onchain_to_onchain_claim() {
4655 // Test that in case of channel closure, we detect the state of output and claim HTLC
4656 // on downstream peer's remote commitment tx.
4657 // First, have C claim an HTLC against its own latest commitment transaction.
4658 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4660 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4663 let chanmon_cfgs = create_chanmon_cfgs(3);
4664 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4665 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4666 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4668 // Create some initial channels
4669 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4670 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4672 // Ensure all nodes are at the same height
4673 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4674 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4675 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4676 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4678 // Rebalance the network a bit by relaying one payment through all the channels ...
4679 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4680 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4682 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4683 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4684 check_spends!(commitment_tx[0], chan_2.3);
4685 nodes[2].node.claim_funds(payment_preimage);
4686 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4687 check_added_monitors!(nodes[2], 1);
4688 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4689 assert!(updates.update_add_htlcs.is_empty());
4690 assert!(updates.update_fail_htlcs.is_empty());
4691 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4692 assert!(updates.update_fail_malformed_htlcs.is_empty());
4694 mine_transaction(&nodes[2], &commitment_tx[0]);
4695 check_closed_broadcast!(nodes[2], true);
4696 check_added_monitors!(nodes[2], 1);
4697 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4699 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4700 assert_eq!(c_txn.len(), 1);
4701 check_spends!(c_txn[0], commitment_tx[0]);
4702 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4703 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4704 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4706 // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
4707 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4708 check_added_monitors!(nodes[1], 1);
4709 let events = nodes[1].node.get_and_clear_pending_events();
4710 assert_eq!(events.len(), 2);
4712 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4713 _ => panic!("Unexpected event"),
4716 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4717 assert_eq!(fee_earned_msat, Some(1000));
4718 assert_eq!(prev_channel_id, Some(chan_1.2));
4719 assert_eq!(claim_from_onchain_tx, true);
4720 assert_eq!(next_channel_id, Some(chan_2.2));
4721 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4723 _ => panic!("Unexpected event"),
4725 check_added_monitors!(nodes[1], 1);
4726 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4727 assert_eq!(msg_events.len(), 3);
4728 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4729 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4731 match nodes_2_event {
4732 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4733 _ => panic!("Unexpected event"),
4736 match nodes_0_event {
4737 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
4738 assert!(update_add_htlcs.is_empty());
4739 assert!(update_fail_htlcs.is_empty());
4740 assert_eq!(update_fulfill_htlcs.len(), 1);
4741 assert!(update_fail_malformed_htlcs.is_empty());
4742 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4744 _ => panic!("Unexpected event"),
4747 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4748 match msg_events[0] {
4749 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4750 _ => panic!("Unexpected event"),
4753 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4754 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4755 mine_transaction(&nodes[1], &commitment_tx[0]);
4756 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4757 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4758 // ChannelMonitor: HTLC-Success tx
4759 assert_eq!(b_txn.len(), 1);
4760 check_spends!(b_txn[0], commitment_tx[0]);
4761 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4762 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4763 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4765 check_closed_broadcast!(nodes[1], true);
4766 check_added_monitors!(nodes[1], 1);
4770 fn test_duplicate_payment_hash_one_failure_one_success() {
4771 // Topology : A --> B --> C --> D
4772 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4773 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4774 // we forward one of the payments onwards to D.
4775 let chanmon_cfgs = create_chanmon_cfgs(4);
4776 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4777 // When this test was written, the default base fee floated based on the HTLC count.
4778 // It is now fixed, so we simply set the fee to the expected value here.
4779 let mut config = test_default_channel_config();
4780 config.channel_config.forwarding_fee_base_msat = 196;
4781 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4782 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4783 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4785 create_announced_chan_between_nodes(&nodes, 0, 1);
4786 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4787 create_announced_chan_between_nodes(&nodes, 2, 3);
4789 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4790 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4791 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4792 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4793 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4795 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4797 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4798 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4799 // script push size limit so that the below script length checks match
4800 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4801 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4802 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4803 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4804 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4806 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4807 assert_eq!(commitment_txn[0].input.len(), 1);
4808 check_spends!(commitment_txn[0], chan_2.3);
4810 mine_transaction(&nodes[1], &commitment_txn[0]);
4811 check_closed_broadcast!(nodes[1], true);
4812 check_added_monitors!(nodes[1], 1);
4813 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4814 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4816 let htlc_timeout_tx;
4817 { // Extract one of the two HTLC-Timeout transaction
4818 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4819 // ChannelMonitor: timeout tx * 2-or-3
4820 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4822 check_spends!(node_txn[0], commitment_txn[0]);
4823 assert_eq!(node_txn[0].input.len(), 1);
4824 assert_eq!(node_txn[0].output.len(), 1);
4826 if node_txn.len() > 2 {
4827 check_spends!(node_txn[1], commitment_txn[0]);
4828 assert_eq!(node_txn[1].input.len(), 1);
4829 assert_eq!(node_txn[1].output.len(), 1);
4830 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4832 check_spends!(node_txn[2], commitment_txn[0]);
4833 assert_eq!(node_txn[2].input.len(), 1);
4834 assert_eq!(node_txn[2].output.len(), 1);
4835 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4837 check_spends!(node_txn[1], commitment_txn[0]);
4838 assert_eq!(node_txn[1].input.len(), 1);
4839 assert_eq!(node_txn[1].output.len(), 1);
4840 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4843 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4844 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4845 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4846 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4847 if node_txn.len() > 2 {
4848 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4849 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4851 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4855 nodes[2].node.claim_funds(our_payment_preimage);
4856 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4858 mine_transaction(&nodes[2], &commitment_txn[0]);
4859 check_added_monitors!(nodes[2], 2);
4860 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4861 let events = nodes[2].node.get_and_clear_pending_msg_events();
4863 MessageSendEvent::UpdateHTLCs { .. } => {},
4864 _ => panic!("Unexpected event"),
4867 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4868 _ => panic!("Unexepected event"),
4870 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4871 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4872 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4873 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4874 assert_eq!(htlc_success_txn[0].input.len(), 1);
4875 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4876 assert_eq!(htlc_success_txn[1].input.len(), 1);
4877 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4878 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4879 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4881 mine_transaction(&nodes[1], &htlc_timeout_tx);
4882 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4883 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4884 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4885 assert!(htlc_updates.update_add_htlcs.is_empty());
4886 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4887 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4888 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4889 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4890 check_added_monitors!(nodes[1], 1);
4892 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4893 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4895 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4897 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4899 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4900 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4901 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4902 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4903 assert!(updates.update_add_htlcs.is_empty());
4904 assert!(updates.update_fail_htlcs.is_empty());
4905 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4906 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4907 assert!(updates.update_fail_malformed_htlcs.is_empty());
4908 check_added_monitors!(nodes[1], 1);
4910 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4911 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4912 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4916 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4917 let chanmon_cfgs = create_chanmon_cfgs(2);
4918 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4919 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4920 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4922 // Create some initial channels
4923 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4925 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4926 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4927 assert_eq!(local_txn.len(), 1);
4928 assert_eq!(local_txn[0].input.len(), 1);
4929 check_spends!(local_txn[0], chan_1.3);
4931 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4932 nodes[1].node.claim_funds(payment_preimage);
4933 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4934 check_added_monitors!(nodes[1], 1);
4936 mine_transaction(&nodes[1], &local_txn[0]);
4937 check_added_monitors!(nodes[1], 1);
4938 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4939 let events = nodes[1].node.get_and_clear_pending_msg_events();
4941 MessageSendEvent::UpdateHTLCs { .. } => {},
4942 _ => panic!("Unexpected event"),
4945 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4946 _ => panic!("Unexepected event"),
4949 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4950 assert_eq!(node_txn.len(), 1);
4951 assert_eq!(node_txn[0].input.len(), 1);
4952 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4953 check_spends!(node_txn[0], local_txn[0]);
4957 mine_transaction(&nodes[1], &node_tx);
4958 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4960 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4961 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4962 assert_eq!(spend_txn.len(), 1);
4963 assert_eq!(spend_txn[0].input.len(), 1);
4964 check_spends!(spend_txn[0], node_tx);
4965 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4968 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4969 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4970 // unrevoked commitment transaction.
4971 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4972 // a remote RAA before they could be failed backwards (and combinations thereof).
4973 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4974 // use the same payment hashes.
4975 // Thus, we use a six-node network:
4980 // And test where C fails back to A/B when D announces its latest commitment transaction
4981 let chanmon_cfgs = create_chanmon_cfgs(6);
4982 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4983 // When this test was written, the default base fee floated based on the HTLC count.
4984 // It is now fixed, so we simply set the fee to the expected value here.
4985 let mut config = test_default_channel_config();
4986 config.channel_config.forwarding_fee_base_msat = 196;
4987 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4988 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4989 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4991 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4992 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4993 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4994 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4995 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4997 // Rebalance and check output sanity...
4998 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4999 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5000 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5002 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5003 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5005 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5007 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5008 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5010 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5012 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5014 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5016 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5017 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5019 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, None).unwrap());
5021 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, None).unwrap());
5024 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5026 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5027 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5030 let (_, payment_hash_6, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5032 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5033 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, None).unwrap());
5035 // Double-check that six of the new HTLC were added
5036 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5037 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5038 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5039 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5041 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5042 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5043 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5044 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5045 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5046 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5047 check_added_monitors!(nodes[4], 0);
5049 let failed_destinations = vec![
5050 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5051 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5052 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5053 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5055 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5056 check_added_monitors!(nodes[4], 1);
5058 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5059 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5060 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5061 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5062 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5063 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5065 // Fail 3rd below-dust and 7th above-dust HTLCs
5066 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5067 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5068 check_added_monitors!(nodes[5], 0);
5070 let failed_destinations_2 = vec![
5071 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5072 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5074 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5075 check_added_monitors!(nodes[5], 1);
5077 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5078 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5079 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5080 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5082 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5084 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5085 let failed_destinations_3 = vec![
5086 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5087 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5088 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5089 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5090 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5091 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5093 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5094 check_added_monitors!(nodes[3], 1);
5095 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5096 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5097 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5098 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5099 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5100 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5101 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5102 if deliver_last_raa {
5103 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5105 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5108 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5109 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5110 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5111 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5113 // We now broadcast the latest commitment transaction, which *should* result in failures for
5114 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5115 // the non-broadcast above-dust HTLCs.
5117 // Alternatively, we may broadcast the previous commitment transaction, which should only
5118 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5119 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5121 if announce_latest {
5122 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5124 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5126 let events = nodes[2].node.get_and_clear_pending_events();
5127 let close_event = if deliver_last_raa {
5128 assert_eq!(events.len(), 2 + 6);
5129 events.last().clone().unwrap()
5131 assert_eq!(events.len(), 1);
5132 events.last().clone().unwrap()
5135 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5136 _ => panic!("Unexpected event"),
5139 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5140 check_closed_broadcast!(nodes[2], true);
5141 if deliver_last_raa {
5142 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5144 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5145 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5147 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5148 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5150 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5153 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5155 check_added_monitors!(nodes[2], 3);
5157 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5158 assert_eq!(cs_msgs.len(), 2);
5159 let mut a_done = false;
5160 for msg in cs_msgs {
5162 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5163 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5164 // should be failed-backwards here.
5165 let target = if *node_id == nodes[0].node.get_our_node_id() {
5166 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5167 for htlc in &updates.update_fail_htlcs {
5168 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5170 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5175 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5176 for htlc in &updates.update_fail_htlcs {
5177 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5179 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5180 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5183 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5184 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5185 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5186 if announce_latest {
5187 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5188 if *node_id == nodes[0].node.get_our_node_id() {
5189 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5192 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5194 _ => panic!("Unexpected event"),
5198 let as_events = nodes[0].node.get_and_clear_pending_events();
5199 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5200 let mut as_failds = HashSet::new();
5201 let mut as_updates = 0;
5202 for event in as_events.iter() {
5203 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5204 assert!(as_failds.insert(*payment_hash));
5205 if *payment_hash != payment_hash_2 {
5206 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5208 assert!(!payment_failed_permanently);
5210 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5213 } else if let &Event::PaymentFailed { .. } = event {
5214 } else { panic!("Unexpected event"); }
5216 assert!(as_failds.contains(&payment_hash_1));
5217 assert!(as_failds.contains(&payment_hash_2));
5218 if announce_latest {
5219 assert!(as_failds.contains(&payment_hash_3));
5220 assert!(as_failds.contains(&payment_hash_5));
5222 assert!(as_failds.contains(&payment_hash_6));
5224 let bs_events = nodes[1].node.get_and_clear_pending_events();
5225 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5226 let mut bs_failds = HashSet::new();
5227 let mut bs_updates = 0;
5228 for event in bs_events.iter() {
5229 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5230 assert!(bs_failds.insert(*payment_hash));
5231 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5232 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5234 assert!(!payment_failed_permanently);
5236 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5239 } else if let &Event::PaymentFailed { .. } = event {
5240 } else { panic!("Unexpected event"); }
5242 assert!(bs_failds.contains(&payment_hash_1));
5243 assert!(bs_failds.contains(&payment_hash_2));
5244 if announce_latest {
5245 assert!(bs_failds.contains(&payment_hash_4));
5247 assert!(bs_failds.contains(&payment_hash_5));
5249 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5250 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5251 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5252 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5253 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5254 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5258 fn test_fail_backwards_latest_remote_announce_a() {
5259 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5263 fn test_fail_backwards_latest_remote_announce_b() {
5264 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5268 fn test_fail_backwards_previous_remote_announce() {
5269 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5270 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5271 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5275 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5276 let chanmon_cfgs = create_chanmon_cfgs(2);
5277 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5278 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5279 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5281 // Create some initial channels
5282 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5284 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5285 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5286 assert_eq!(local_txn[0].input.len(), 1);
5287 check_spends!(local_txn[0], chan_1.3);
5289 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5290 mine_transaction(&nodes[0], &local_txn[0]);
5291 check_closed_broadcast!(nodes[0], true);
5292 check_added_monitors!(nodes[0], 1);
5293 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5294 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5296 let htlc_timeout = {
5297 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5298 assert_eq!(node_txn.len(), 1);
5299 assert_eq!(node_txn[0].input.len(), 1);
5300 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5301 check_spends!(node_txn[0], local_txn[0]);
5305 mine_transaction(&nodes[0], &htlc_timeout);
5306 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5307 expect_payment_failed!(nodes[0], our_payment_hash, false);
5309 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5310 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5311 assert_eq!(spend_txn.len(), 3);
5312 check_spends!(spend_txn[0], local_txn[0]);
5313 assert_eq!(spend_txn[1].input.len(), 1);
5314 check_spends!(spend_txn[1], htlc_timeout);
5315 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5316 assert_eq!(spend_txn[2].input.len(), 2);
5317 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5318 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5319 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5323 fn test_key_derivation_params() {
5324 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5325 // manager rotation to test that `channel_keys_id` returned in
5326 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5327 // then derive a `delayed_payment_key`.
5329 let chanmon_cfgs = create_chanmon_cfgs(3);
5331 // We manually create the node configuration to backup the seed.
5332 let seed = [42; 32];
5333 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5334 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5335 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5336 let scorer = Mutex::new(test_utils::TestScorer::new());
5337 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5338 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5339 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5340 node_cfgs.remove(0);
5341 node_cfgs.insert(0, node);
5343 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5344 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5346 // Create some initial channels
5347 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5349 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5350 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5351 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5353 // Ensure all nodes are at the same height
5354 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5355 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5356 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5357 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5359 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5360 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5361 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5362 assert_eq!(local_txn_1[0].input.len(), 1);
5363 check_spends!(local_txn_1[0], chan_1.3);
5365 // We check funding pubkey are unique
5366 let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5367 let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5368 if from_0_funding_key_0 == from_1_funding_key_0
5369 || from_0_funding_key_0 == from_1_funding_key_1
5370 || from_0_funding_key_1 == from_1_funding_key_0
5371 || from_0_funding_key_1 == from_1_funding_key_1 {
5372 panic!("Funding pubkeys aren't unique");
5375 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5376 mine_transaction(&nodes[0], &local_txn_1[0]);
5377 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5378 check_closed_broadcast!(nodes[0], true);
5379 check_added_monitors!(nodes[0], 1);
5380 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5382 let htlc_timeout = {
5383 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5384 assert_eq!(node_txn.len(), 1);
5385 assert_eq!(node_txn[0].input.len(), 1);
5386 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5387 check_spends!(node_txn[0], local_txn_1[0]);
5391 mine_transaction(&nodes[0], &htlc_timeout);
5392 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5393 expect_payment_failed!(nodes[0], our_payment_hash, false);
5395 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5396 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5397 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5398 assert_eq!(spend_txn.len(), 3);
5399 check_spends!(spend_txn[0], local_txn_1[0]);
5400 assert_eq!(spend_txn[1].input.len(), 1);
5401 check_spends!(spend_txn[1], htlc_timeout);
5402 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5403 assert_eq!(spend_txn[2].input.len(), 2);
5404 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5405 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5406 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5410 fn test_static_output_closing_tx() {
5411 let chanmon_cfgs = create_chanmon_cfgs(2);
5412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5414 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5416 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5418 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5419 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5421 mine_transaction(&nodes[0], &closing_tx);
5422 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5423 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5425 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5426 assert_eq!(spend_txn.len(), 1);
5427 check_spends!(spend_txn[0], closing_tx);
5429 mine_transaction(&nodes[1], &closing_tx);
5430 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5431 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5433 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5434 assert_eq!(spend_txn.len(), 1);
5435 check_spends!(spend_txn[0], closing_tx);
5438 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5439 let chanmon_cfgs = create_chanmon_cfgs(2);
5440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5442 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5443 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5445 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5447 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5448 // present in B's local commitment transaction, but none of A's commitment transactions.
5449 nodes[1].node.claim_funds(payment_preimage);
5450 check_added_monitors!(nodes[1], 1);
5451 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5453 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5454 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5455 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5457 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5458 check_added_monitors!(nodes[0], 1);
5459 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5460 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5461 check_added_monitors!(nodes[1], 1);
5463 let starting_block = nodes[1].best_block_info();
5464 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5465 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5466 connect_block(&nodes[1], &block);
5467 block.header.prev_blockhash = block.block_hash();
5469 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5470 check_closed_broadcast!(nodes[1], true);
5471 check_added_monitors!(nodes[1], 1);
5472 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5475 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5476 let chanmon_cfgs = create_chanmon_cfgs(2);
5477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5479 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5480 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5482 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5483 nodes[0].node.send_payment_with_route(&route, payment_hash,
5484 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5485 check_added_monitors!(nodes[0], 1);
5487 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5489 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5490 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5491 // to "time out" the HTLC.
5493 let starting_block = nodes[1].best_block_info();
5494 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5496 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5497 connect_block(&nodes[0], &block);
5498 block.header.prev_blockhash = block.block_hash();
5500 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5501 check_closed_broadcast!(nodes[0], true);
5502 check_added_monitors!(nodes[0], 1);
5503 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5506 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5507 let chanmon_cfgs = create_chanmon_cfgs(3);
5508 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5509 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5510 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5511 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5513 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5514 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5515 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5516 // actually revoked.
5517 let htlc_value = if use_dust { 50000 } else { 3000000 };
5518 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5519 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5520 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5521 check_added_monitors!(nodes[1], 1);
5523 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5524 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5525 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5526 check_added_monitors!(nodes[0], 1);
5527 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5528 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5529 check_added_monitors!(nodes[1], 1);
5530 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5531 check_added_monitors!(nodes[1], 1);
5532 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5534 if check_revoke_no_close {
5535 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5536 check_added_monitors!(nodes[0], 1);
5539 let starting_block = nodes[1].best_block_info();
5540 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5541 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5542 connect_block(&nodes[0], &block);
5543 block.header.prev_blockhash = block.block_hash();
5545 if !check_revoke_no_close {
5546 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5547 check_closed_broadcast!(nodes[0], true);
5548 check_added_monitors!(nodes[0], 1);
5549 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5551 expect_payment_failed!(nodes[0], our_payment_hash, true);
5555 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5556 // There are only a few cases to test here:
5557 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5558 // broadcastable commitment transactions result in channel closure,
5559 // * its included in an unrevoked-but-previous remote commitment transaction,
5560 // * its included in the latest remote or local commitment transactions.
5561 // We test each of the three possible commitment transactions individually and use both dust and
5563 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5564 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5565 // tested for at least one of the cases in other tests.
5567 fn htlc_claim_single_commitment_only_a() {
5568 do_htlc_claim_local_commitment_only(true);
5569 do_htlc_claim_local_commitment_only(false);
5571 do_htlc_claim_current_remote_commitment_only(true);
5572 do_htlc_claim_current_remote_commitment_only(false);
5576 fn htlc_claim_single_commitment_only_b() {
5577 do_htlc_claim_previous_remote_commitment_only(true, false);
5578 do_htlc_claim_previous_remote_commitment_only(false, false);
5579 do_htlc_claim_previous_remote_commitment_only(true, true);
5580 do_htlc_claim_previous_remote_commitment_only(false, true);
5585 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5586 let chanmon_cfgs = create_chanmon_cfgs(2);
5587 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5588 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5589 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5590 // Force duplicate randomness for every get-random call
5591 for node in nodes.iter() {
5592 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5595 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5596 let channel_value_satoshis=10000;
5597 let push_msat=10001;
5598 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5599 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5600 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5601 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5603 // Create a second channel with the same random values. This used to panic due to a colliding
5604 // channel_id, but now panics due to a colliding outbound SCID alias.
5605 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5609 fn bolt2_open_channel_sending_node_checks_part2() {
5610 let chanmon_cfgs = create_chanmon_cfgs(2);
5611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5613 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5615 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5616 let channel_value_satoshis=2^24;
5617 let push_msat=10001;
5618 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5620 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5621 let channel_value_satoshis=10000;
5622 // Test when push_msat is equal to 1000 * funding_satoshis.
5623 let push_msat=1000*channel_value_satoshis+1;
5624 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5626 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5627 let channel_value_satoshis=10000;
5628 let push_msat=10001;
5629 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5630 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5631 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5633 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5634 // Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
5635 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5637 // BOLT #2 spec: Sending node should set to_self_delay sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehaviour by the receiver.
5638 assert!(BREAKDOWN_TIMEOUT>0);
5639 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5641 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5642 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5643 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5645 // BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
5646 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5647 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5648 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5649 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5650 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5654 fn bolt2_open_channel_sane_dust_limit() {
5655 let chanmon_cfgs = create_chanmon_cfgs(2);
5656 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5657 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5658 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5660 let channel_value_satoshis=1000000;
5661 let push_msat=10001;
5662 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5663 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5664 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5665 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5667 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5668 let events = nodes[1].node.get_and_clear_pending_msg_events();
5669 let err_msg = match events[0] {
5670 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5673 _ => panic!("Unexpected event"),
5675 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5678 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5679 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5680 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5681 // is no longer affordable once it's freed.
5683 fn test_fail_holding_cell_htlc_upon_free() {
5684 let chanmon_cfgs = create_chanmon_cfgs(2);
5685 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5686 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5687 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5688 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5690 // First nodes[0] generates an update_fee, setting the channel's
5691 // pending_update_fee.
5693 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5694 *feerate_lock += 20;
5696 nodes[0].node.timer_tick_occurred();
5697 check_added_monitors!(nodes[0], 1);
5699 let events = nodes[0].node.get_and_clear_pending_msg_events();
5700 assert_eq!(events.len(), 1);
5701 let (update_msg, commitment_signed) = match events[0] {
5702 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5703 (update_fee.as_ref(), commitment_signed)
5705 _ => panic!("Unexpected event"),
5708 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5710 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5711 let channel_reserve = chan_stat.channel_reserve_msat;
5712 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5713 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5715 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5716 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5717 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5719 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5720 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5721 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5722 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5723 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5725 // Flush the pending fee update.
5726 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5727 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5728 check_added_monitors!(nodes[1], 1);
5729 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5730 check_added_monitors!(nodes[0], 1);
5732 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5733 // HTLC, but now that the fee has been raised the payment will now fail, causing
5734 // us to surface its failure to the user.
5735 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5736 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5737 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5738 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5739 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5740 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5742 // Check that the payment failed to be sent out.
5743 let events = nodes[0].node.get_and_clear_pending_events();
5744 assert_eq!(events.len(), 2);
5746 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5747 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5748 assert_eq!(our_payment_hash.clone(), *payment_hash);
5749 assert_eq!(*payment_failed_permanently, false);
5750 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5752 _ => panic!("Unexpected event"),
5755 &Event::PaymentFailed { ref payment_hash, .. } => {
5756 assert_eq!(our_payment_hash.clone(), *payment_hash);
5758 _ => panic!("Unexpected event"),
5762 // Test that if multiple HTLCs are released from the holding cell and one is
5763 // valid but the other is no longer valid upon release, the valid HTLC can be
5764 // successfully completed while the other one fails as expected.
5766 fn test_free_and_fail_holding_cell_htlcs() {
5767 let chanmon_cfgs = create_chanmon_cfgs(2);
5768 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5769 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5770 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5771 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5773 // First nodes[0] generates an update_fee, setting the channel's
5774 // pending_update_fee.
5776 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5777 *feerate_lock += 200;
5779 nodes[0].node.timer_tick_occurred();
5780 check_added_monitors!(nodes[0], 1);
5782 let events = nodes[0].node.get_and_clear_pending_msg_events();
5783 assert_eq!(events.len(), 1);
5784 let (update_msg, commitment_signed) = match events[0] {
5785 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5786 (update_fee.as_ref(), commitment_signed)
5788 _ => panic!("Unexpected event"),
5791 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5793 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5794 let channel_reserve = chan_stat.channel_reserve_msat;
5795 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5796 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5798 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5800 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5801 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5802 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5804 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5805 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5806 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5807 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5808 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5809 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5810 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5811 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5812 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5813 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5815 // Flush the pending fee update.
5816 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5817 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5818 check_added_monitors!(nodes[1], 1);
5819 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5820 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5821 check_added_monitors!(nodes[0], 2);
5823 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5824 // but now that the fee has been raised the second payment will now fail, causing us
5825 // to surface its failure to the user. The first payment should succeed.
5826 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5827 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5828 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);
5829 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5830 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5831 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5833 // Check that the second payment failed to be sent out.
5834 let events = nodes[0].node.get_and_clear_pending_events();
5835 assert_eq!(events.len(), 2);
5837 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5838 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5839 assert_eq!(payment_hash_2.clone(), *payment_hash);
5840 assert_eq!(*payment_failed_permanently, false);
5841 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5843 _ => panic!("Unexpected event"),
5846 &Event::PaymentFailed { ref payment_hash, .. } => {
5847 assert_eq!(payment_hash_2.clone(), *payment_hash);
5849 _ => panic!("Unexpected event"),
5852 // Complete the first payment and the RAA from the fee update.
5853 let (payment_event, send_raa_event) = {
5854 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5855 assert_eq!(msgs.len(), 2);
5856 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5858 let raa = match send_raa_event {
5859 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5860 _ => panic!("Unexpected event"),
5862 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5863 check_added_monitors!(nodes[1], 1);
5864 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5865 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5866 let events = nodes[1].node.get_and_clear_pending_events();
5867 assert_eq!(events.len(), 1);
5869 Event::PendingHTLCsForwardable { .. } => {},
5870 _ => panic!("Unexpected event"),
5872 nodes[1].node.process_pending_htlc_forwards();
5873 let events = nodes[1].node.get_and_clear_pending_events();
5874 assert_eq!(events.len(), 1);
5876 Event::PaymentClaimable { .. } => {},
5877 _ => panic!("Unexpected event"),
5879 nodes[1].node.claim_funds(payment_preimage_1);
5880 check_added_monitors!(nodes[1], 1);
5881 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5883 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5884 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5885 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5886 expect_payment_sent!(nodes[0], payment_preimage_1);
5889 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5890 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5891 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5894 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5895 let chanmon_cfgs = create_chanmon_cfgs(3);
5896 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5897 // Avoid having to include routing fees in calculations
5898 let mut config = test_default_channel_config();
5899 config.channel_config.forwarding_fee_base_msat = 0;
5900 config.channel_config.forwarding_fee_proportional_millionths = 0;
5901 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5902 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5903 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5904 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5906 // First nodes[1] generates an update_fee, setting the channel's
5907 // pending_update_fee.
5909 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5910 *feerate_lock += 20;
5912 nodes[1].node.timer_tick_occurred();
5913 check_added_monitors!(nodes[1], 1);
5915 let events = nodes[1].node.get_and_clear_pending_msg_events();
5916 assert_eq!(events.len(), 1);
5917 let (update_msg, commitment_signed) = match events[0] {
5918 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5919 (update_fee.as_ref(), commitment_signed)
5921 _ => panic!("Unexpected event"),
5924 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5926 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5927 let channel_reserve = chan_stat.channel_reserve_msat;
5928 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5929 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5931 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5932 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5933 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5934 let payment_event = {
5935 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5936 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5937 check_added_monitors!(nodes[0], 1);
5939 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5940 assert_eq!(events.len(), 1);
5942 SendEvent::from_event(events.remove(0))
5944 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5945 check_added_monitors!(nodes[1], 0);
5946 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5947 expect_pending_htlcs_forwardable!(nodes[1]);
5949 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5950 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5952 // Flush the pending fee update.
5953 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5954 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5955 check_added_monitors!(nodes[2], 1);
5956 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5957 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5958 check_added_monitors!(nodes[1], 2);
5960 // A final RAA message is generated to finalize the fee update.
5961 let events = nodes[1].node.get_and_clear_pending_msg_events();
5962 assert_eq!(events.len(), 1);
5964 let raa_msg = match &events[0] {
5965 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5968 _ => panic!("Unexpected event"),
5971 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5972 check_added_monitors!(nodes[2], 1);
5973 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5975 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5976 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5977 assert_eq!(process_htlc_forwards_event.len(), 2);
5978 match &process_htlc_forwards_event[0] {
5979 &Event::PendingHTLCsForwardable { .. } => {},
5980 _ => panic!("Unexpected event"),
5983 // In response, we call ChannelManager's process_pending_htlc_forwards
5984 nodes[1].node.process_pending_htlc_forwards();
5985 check_added_monitors!(nodes[1], 1);
5987 // This causes the HTLC to be failed backwards.
5988 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5989 assert_eq!(fail_event.len(), 1);
5990 let (fail_msg, commitment_signed) = match &fail_event[0] {
5991 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5992 assert_eq!(updates.update_add_htlcs.len(), 0);
5993 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5994 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5995 assert_eq!(updates.update_fail_htlcs.len(), 1);
5996 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5998 _ => panic!("Unexpected event"),
6001 // Pass the failure messages back to nodes[0].
6002 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6003 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6005 // Complete the HTLC failure+removal process.
6006 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6007 check_added_monitors!(nodes[0], 1);
6008 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6009 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6010 check_added_monitors!(nodes[1], 2);
6011 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6012 assert_eq!(final_raa_event.len(), 1);
6013 let raa = match &final_raa_event[0] {
6014 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6015 _ => panic!("Unexpected event"),
6017 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6018 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6019 check_added_monitors!(nodes[0], 1);
6022 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6023 // 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.
6024 //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.
6027 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6028 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6029 let chanmon_cfgs = create_chanmon_cfgs(2);
6030 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6031 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6032 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6033 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6035 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6036 route.paths[0].hops[0].fee_msat = 100;
6038 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6039 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6040 ), true, APIError::ChannelUnavailable { ref err },
6041 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6042 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6043 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6047 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6048 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6049 let chanmon_cfgs = create_chanmon_cfgs(2);
6050 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6051 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6052 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6053 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6055 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6056 route.paths[0].hops[0].fee_msat = 0;
6057 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6058 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6059 true, APIError::ChannelUnavailable { ref err },
6060 assert_eq!(err, "Cannot send 0-msat HTLC"));
6062 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6063 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6067 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6068 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6069 let chanmon_cfgs = create_chanmon_cfgs(2);
6070 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6071 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6072 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6073 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6075 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6076 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6077 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6078 check_added_monitors!(nodes[0], 1);
6079 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6080 updates.update_add_htlcs[0].amount_msat = 0;
6082 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6083 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6084 check_closed_broadcast!(nodes[1], true).unwrap();
6085 check_added_monitors!(nodes[1], 1);
6086 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6090 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6091 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6092 //It is enforced when constructing a route.
6093 let chanmon_cfgs = create_chanmon_cfgs(2);
6094 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6095 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6096 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6097 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6099 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6100 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6101 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6102 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6103 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6104 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6105 ), true, APIError::InvalidRoute { ref err },
6106 assert_eq!(err, &"Channel CLTV overflowed?"));
6110 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6111 //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.
6112 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6113 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6114 let chanmon_cfgs = create_chanmon_cfgs(2);
6115 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6116 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6117 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6118 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6119 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6120 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6122 // Fetch a route in advance as we will be unable to once we're unable to send.
6123 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6124 for i in 0..max_accepted_htlcs {
6125 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6126 let payment_event = {
6127 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6128 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6129 check_added_monitors!(nodes[0], 1);
6131 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6132 assert_eq!(events.len(), 1);
6133 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6134 assert_eq!(htlcs[0].htlc_id, i);
6138 SendEvent::from_event(events.remove(0))
6140 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6141 check_added_monitors!(nodes[1], 0);
6142 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6144 expect_pending_htlcs_forwardable!(nodes[1]);
6145 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6147 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6148 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6149 ), true, APIError::ChannelUnavailable { ref err },
6150 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6152 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6153 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6157 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6158 //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.
6159 let chanmon_cfgs = create_chanmon_cfgs(2);
6160 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6161 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6162 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6163 let channel_value = 100000;
6164 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6165 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6167 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6169 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6170 // Manually create a route over our max in flight (which our router normally automatically
6172 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6173 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6174 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6175 ), true, APIError::ChannelUnavailable { ref err },
6176 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6178 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6179 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
6181 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6184 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6186 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6187 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6188 let chanmon_cfgs = create_chanmon_cfgs(2);
6189 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6190 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6191 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6192 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6193 let htlc_minimum_msat: u64;
6195 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6196 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6197 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6198 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6201 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6202 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6203 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6204 check_added_monitors!(nodes[0], 1);
6205 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6206 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6207 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6208 assert!(nodes[1].node.list_channels().is_empty());
6209 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6210 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()));
6211 check_added_monitors!(nodes[1], 1);
6212 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6216 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6217 //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
6218 let chanmon_cfgs = create_chanmon_cfgs(2);
6219 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6220 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6221 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6222 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6224 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6225 let channel_reserve = chan_stat.channel_reserve_msat;
6226 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6227 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6228 // The 2* and +1 are for the fee spike reserve.
6229 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6231 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6232 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6233 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6234 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6235 check_added_monitors!(nodes[0], 1);
6236 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6238 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6239 // at this time channel-initiatee receivers are not required to enforce that senders
6240 // respect the fee_spike_reserve.
6241 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6242 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6244 assert!(nodes[1].node.list_channels().is_empty());
6245 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6246 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6247 check_added_monitors!(nodes[1], 1);
6248 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6252 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6253 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6254 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6255 let chanmon_cfgs = create_chanmon_cfgs(2);
6256 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6257 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6258 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6259 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6261 let send_amt = 3999999;
6262 let (mut route, our_payment_hash, _, our_payment_secret) =
6263 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6264 route.paths[0].hops[0].fee_msat = send_amt;
6265 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6266 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6267 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6268 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6269 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6270 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6272 let mut msg = msgs::UpdateAddHTLC {
6276 payment_hash: our_payment_hash,
6277 cltv_expiry: htlc_cltv,
6278 onion_routing_packet: onion_packet.clone(),
6282 msg.htlc_id = i as u64;
6283 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6285 msg.htlc_id = (50) as u64;
6286 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6288 assert!(nodes[1].node.list_channels().is_empty());
6289 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6290 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6291 check_added_monitors!(nodes[1], 1);
6292 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6296 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6297 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6298 let chanmon_cfgs = create_chanmon_cfgs(2);
6299 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6300 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6301 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6302 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6304 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6305 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6306 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6307 check_added_monitors!(nodes[0], 1);
6308 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6309 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;
6310 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6312 assert!(nodes[1].node.list_channels().is_empty());
6313 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6314 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6315 check_added_monitors!(nodes[1], 1);
6316 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6320 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6321 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6322 let chanmon_cfgs = create_chanmon_cfgs(2);
6323 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6327 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6328 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6329 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6330 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6331 check_added_monitors!(nodes[0], 1);
6332 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6333 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6334 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6336 assert!(nodes[1].node.list_channels().is_empty());
6337 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6338 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6339 check_added_monitors!(nodes[1], 1);
6340 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6344 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6345 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6346 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6347 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6348 let chanmon_cfgs = create_chanmon_cfgs(2);
6349 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6350 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6351 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6353 create_announced_chan_between_nodes(&nodes, 0, 1);
6354 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6355 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6356 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6357 check_added_monitors!(nodes[0], 1);
6358 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6359 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6361 //Disconnect and Reconnect
6362 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6363 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6364 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();
6365 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6366 assert_eq!(reestablish_1.len(), 1);
6367 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();
6368 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6369 assert_eq!(reestablish_2.len(), 1);
6370 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6371 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6372 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6373 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6376 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6377 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6378 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6379 check_added_monitors!(nodes[1], 1);
6380 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6382 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6384 assert!(nodes[1].node.list_channels().is_empty());
6385 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6386 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6387 check_added_monitors!(nodes[1], 1);
6388 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6392 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6393 //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.
6395 let chanmon_cfgs = create_chanmon_cfgs(2);
6396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6398 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6399 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6400 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6401 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6402 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6404 check_added_monitors!(nodes[0], 1);
6405 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6406 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6408 let update_msg = msgs::UpdateFulfillHTLC{
6411 payment_preimage: our_payment_preimage,
6414 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6416 assert!(nodes[0].node.list_channels().is_empty());
6417 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6418 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()));
6419 check_added_monitors!(nodes[0], 1);
6420 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6424 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6425 //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.
6427 let chanmon_cfgs = create_chanmon_cfgs(2);
6428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6430 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6431 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6433 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6434 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6435 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6436 check_added_monitors!(nodes[0], 1);
6437 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6438 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6440 let update_msg = msgs::UpdateFailHTLC{
6443 reason: msgs::OnionErrorPacket { data: Vec::new()},
6446 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6448 assert!(nodes[0].node.list_channels().is_empty());
6449 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6450 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()));
6451 check_added_monitors!(nodes[0], 1);
6452 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6456 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6457 //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.
6459 let chanmon_cfgs = create_chanmon_cfgs(2);
6460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6462 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6463 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6465 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6466 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6467 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6468 check_added_monitors!(nodes[0], 1);
6469 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6470 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6471 let update_msg = msgs::UpdateFailMalformedHTLC{
6474 sha256_of_onion: [1; 32],
6475 failure_code: 0x8000,
6478 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6480 assert!(nodes[0].node.list_channels().is_empty());
6481 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6482 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()));
6483 check_added_monitors!(nodes[0], 1);
6484 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6488 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6489 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6491 let chanmon_cfgs = create_chanmon_cfgs(2);
6492 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6493 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6494 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6495 create_announced_chan_between_nodes(&nodes, 0, 1);
6497 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6499 nodes[1].node.claim_funds(our_payment_preimage);
6500 check_added_monitors!(nodes[1], 1);
6501 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6503 let events = nodes[1].node.get_and_clear_pending_msg_events();
6504 assert_eq!(events.len(), 1);
6505 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6507 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, .. } } => {
6508 assert!(update_add_htlcs.is_empty());
6509 assert_eq!(update_fulfill_htlcs.len(), 1);
6510 assert!(update_fail_htlcs.is_empty());
6511 assert!(update_fail_malformed_htlcs.is_empty());
6512 assert!(update_fee.is_none());
6513 update_fulfill_htlcs[0].clone()
6515 _ => panic!("Unexpected event"),
6519 update_fulfill_msg.htlc_id = 1;
6521 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6523 assert!(nodes[0].node.list_channels().is_empty());
6524 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6525 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6526 check_added_monitors!(nodes[0], 1);
6527 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6531 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6532 //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.
6534 let chanmon_cfgs = create_chanmon_cfgs(2);
6535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6537 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6538 create_announced_chan_between_nodes(&nodes, 0, 1);
6540 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6542 nodes[1].node.claim_funds(our_payment_preimage);
6543 check_added_monitors!(nodes[1], 1);
6544 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6546 let events = nodes[1].node.get_and_clear_pending_msg_events();
6547 assert_eq!(events.len(), 1);
6548 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6550 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, .. } } => {
6551 assert!(update_add_htlcs.is_empty());
6552 assert_eq!(update_fulfill_htlcs.len(), 1);
6553 assert!(update_fail_htlcs.is_empty());
6554 assert!(update_fail_malformed_htlcs.is_empty());
6555 assert!(update_fee.is_none());
6556 update_fulfill_htlcs[0].clone()
6558 _ => panic!("Unexpected event"),
6562 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6564 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6566 assert!(nodes[0].node.list_channels().is_empty());
6567 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6568 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6569 check_added_monitors!(nodes[0], 1);
6570 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6574 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6575 //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.
6577 let chanmon_cfgs = create_chanmon_cfgs(2);
6578 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6579 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6580 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6581 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6583 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6584 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6585 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6586 check_added_monitors!(nodes[0], 1);
6588 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6589 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6591 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6592 check_added_monitors!(nodes[1], 0);
6593 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6595 let events = nodes[1].node.get_and_clear_pending_msg_events();
6597 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6599 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, .. } } => {
6600 assert!(update_add_htlcs.is_empty());
6601 assert!(update_fulfill_htlcs.is_empty());
6602 assert!(update_fail_htlcs.is_empty());
6603 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6604 assert!(update_fee.is_none());
6605 update_fail_malformed_htlcs[0].clone()
6607 _ => panic!("Unexpected event"),
6610 update_msg.failure_code &= !0x8000;
6611 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6613 assert!(nodes[0].node.list_channels().is_empty());
6614 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6615 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6616 check_added_monitors!(nodes[0], 1);
6617 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6621 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6622 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6623 // * 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.
6625 let chanmon_cfgs = create_chanmon_cfgs(3);
6626 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6627 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6628 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6629 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6630 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6632 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6635 let mut payment_event = {
6636 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6637 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6638 check_added_monitors!(nodes[0], 1);
6639 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6640 assert_eq!(events.len(), 1);
6641 SendEvent::from_event(events.remove(0))
6643 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6644 check_added_monitors!(nodes[1], 0);
6645 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6646 expect_pending_htlcs_forwardable!(nodes[1]);
6647 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6648 assert_eq!(events_2.len(), 1);
6649 check_added_monitors!(nodes[1], 1);
6650 payment_event = SendEvent::from_event(events_2.remove(0));
6651 assert_eq!(payment_event.msgs.len(), 1);
6654 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6655 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6656 check_added_monitors!(nodes[2], 0);
6657 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6659 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6660 assert_eq!(events_3.len(), 1);
6661 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6663 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 } } => {
6664 assert!(update_add_htlcs.is_empty());
6665 assert!(update_fulfill_htlcs.is_empty());
6666 assert!(update_fail_htlcs.is_empty());
6667 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6668 assert!(update_fee.is_none());
6669 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6671 _ => panic!("Unexpected event"),
6675 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6677 check_added_monitors!(nodes[1], 0);
6678 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6679 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 }]);
6680 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6681 assert_eq!(events_4.len(), 1);
6683 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6685 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, .. } } => {
6686 assert!(update_add_htlcs.is_empty());
6687 assert!(update_fulfill_htlcs.is_empty());
6688 assert_eq!(update_fail_htlcs.len(), 1);
6689 assert!(update_fail_malformed_htlcs.is_empty());
6690 assert!(update_fee.is_none());
6692 _ => panic!("Unexpected event"),
6695 check_added_monitors!(nodes[1], 1);
6699 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6700 let chanmon_cfgs = create_chanmon_cfgs(3);
6701 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6702 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6703 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6704 create_announced_chan_between_nodes(&nodes, 0, 1);
6705 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6707 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6710 let mut payment_event = {
6711 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6712 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6713 check_added_monitors!(nodes[0], 1);
6714 SendEvent::from_node(&nodes[0])
6717 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6718 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6719 expect_pending_htlcs_forwardable!(nodes[1]);
6720 check_added_monitors!(nodes[1], 1);
6721 payment_event = SendEvent::from_node(&nodes[1]);
6722 assert_eq!(payment_event.msgs.len(), 1);
6725 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6726 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6727 check_added_monitors!(nodes[2], 0);
6728 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6730 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6731 assert_eq!(events_3.len(), 1);
6733 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6734 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6735 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6736 update_msg.failure_code |= 0x2000;
6738 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6739 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6741 _ => panic!("Unexpected event"),
6744 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6745 vec![HTLCDestination::NextHopChannel {
6746 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6747 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6748 assert_eq!(events_4.len(), 1);
6749 check_added_monitors!(nodes[1], 1);
6752 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6753 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6754 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6756 _ => panic!("Unexpected event"),
6759 let events_5 = nodes[0].node.get_and_clear_pending_events();
6760 assert_eq!(events_5.len(), 2);
6762 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6763 // the node originating the error to its next hop.
6765 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6767 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6768 assert!(is_permanent);
6769 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6771 _ => panic!("Unexpected event"),
6774 Event::PaymentFailed { payment_hash, .. } => {
6775 assert_eq!(payment_hash, our_payment_hash);
6777 _ => panic!("Unexpected event"),
6780 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6783 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6784 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6785 // 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
6786 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6788 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6789 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6790 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6791 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6792 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6793 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6795 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6796 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6798 // We route 2 dust-HTLCs between A and B
6799 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6800 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6801 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6803 // Cache one local commitment tx as previous
6804 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6806 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6807 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6808 check_added_monitors!(nodes[1], 0);
6809 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6810 check_added_monitors!(nodes[1], 1);
6812 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6813 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6814 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6815 check_added_monitors!(nodes[0], 1);
6817 // Cache one local commitment tx as lastest
6818 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6820 let events = nodes[0].node.get_and_clear_pending_msg_events();
6822 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6823 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6825 _ => panic!("Unexpected event"),
6828 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6829 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6831 _ => panic!("Unexpected event"),
6834 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6835 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6836 if announce_latest {
6837 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6839 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6842 check_closed_broadcast!(nodes[0], true);
6843 check_added_monitors!(nodes[0], 1);
6844 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6846 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6847 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6848 let events = nodes[0].node.get_and_clear_pending_events();
6849 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6850 assert_eq!(events.len(), 4);
6851 let mut first_failed = false;
6852 for event in events {
6854 Event::PaymentPathFailed { payment_hash, .. } => {
6855 if payment_hash == payment_hash_1 {
6856 assert!(!first_failed);
6857 first_failed = true;
6859 assert_eq!(payment_hash, payment_hash_2);
6862 Event::PaymentFailed { .. } => {}
6863 _ => panic!("Unexpected event"),
6869 fn test_failure_delay_dust_htlc_local_commitment() {
6870 do_test_failure_delay_dust_htlc_local_commitment(true);
6871 do_test_failure_delay_dust_htlc_local_commitment(false);
6874 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6875 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6876 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6877 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6878 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6879 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6880 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6882 let chanmon_cfgs = create_chanmon_cfgs(3);
6883 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6884 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6885 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6886 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6888 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6889 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6891 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6892 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6894 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6895 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6897 // We revoked bs_commitment_tx
6899 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6900 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6903 let mut timeout_tx = Vec::new();
6905 // We fail dust-HTLC 1 by broadcast of local commitment tx
6906 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6907 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6908 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6909 expect_payment_failed!(nodes[0], dust_hash, false);
6911 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6912 check_closed_broadcast!(nodes[0], true);
6913 check_added_monitors!(nodes[0], 1);
6914 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6915 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6916 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6917 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6918 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6919 mine_transaction(&nodes[0], &timeout_tx[0]);
6920 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6921 expect_payment_failed!(nodes[0], non_dust_hash, false);
6923 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6924 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6925 check_closed_broadcast!(nodes[0], true);
6926 check_added_monitors!(nodes[0], 1);
6927 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6928 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6930 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6931 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6932 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6933 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6934 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6935 // dust HTLC should have been failed.
6936 expect_payment_failed!(nodes[0], dust_hash, false);
6939 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6941 assert_eq!(timeout_tx[0].lock_time.0, 11);
6943 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6944 mine_transaction(&nodes[0], &timeout_tx[0]);
6945 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6946 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6947 expect_payment_failed!(nodes[0], non_dust_hash, false);
6952 fn test_sweep_outbound_htlc_failure_update() {
6953 do_test_sweep_outbound_htlc_failure_update(false, true);
6954 do_test_sweep_outbound_htlc_failure_update(false, false);
6955 do_test_sweep_outbound_htlc_failure_update(true, false);
6959 fn test_user_configurable_csv_delay() {
6960 // We test our channel constructors yield errors when we pass them absurd csv delay
6962 let mut low_our_to_self_config = UserConfig::default();
6963 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6964 let mut high_their_to_self_config = UserConfig::default();
6965 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6966 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6967 let chanmon_cfgs = create_chanmon_cfgs(2);
6968 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6969 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6970 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6972 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6973 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6974 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6975 &low_our_to_self_config, 0, 42)
6978 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())); },
6979 _ => panic!("Unexpected event"),
6981 } else { assert!(false) }
6983 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6984 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6985 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6986 open_channel.to_self_delay = 200;
6987 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6988 &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,
6989 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6992 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())); },
6993 _ => panic!("Unexpected event"),
6995 } else { assert!(false); }
6997 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6998 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6999 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()));
7000 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7001 accept_channel.to_self_delay = 200;
7002 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7004 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7006 &ErrorAction::SendErrorMessage { ref msg } => {
7007 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()));
7008 reason_msg = msg.data.clone();
7012 } else { panic!(); }
7013 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7015 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7016 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7017 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7018 open_channel.to_self_delay = 200;
7019 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7020 &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,
7021 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7024 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())); },
7025 _ => panic!("Unexpected event"),
7027 } else { assert!(false); }
7031 fn test_check_htlc_underpaying() {
7032 // Send payment through A -> B but A is maliciously
7033 // sending a probe payment (i.e less than expected value0
7034 // to B, B should refuse payment.
7036 let chanmon_cfgs = create_chanmon_cfgs(2);
7037 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7038 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7039 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7041 // Create some initial channels
7042 create_announced_chan_between_nodes(&nodes, 0, 1);
7044 let scorer = test_utils::TestScorer::new();
7045 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7046 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();
7047 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();
7048 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7049 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7050 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7051 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7052 check_added_monitors!(nodes[0], 1);
7054 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7055 assert_eq!(events.len(), 1);
7056 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7057 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7058 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7060 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7061 // and then will wait a second random delay before failing the HTLC back:
7062 expect_pending_htlcs_forwardable!(nodes[1]);
7063 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7065 // Node 3 is expecting payment of 100_000 but received 10_000,
7066 // it should fail htlc like we didn't know the preimage.
7067 nodes[1].node.process_pending_htlc_forwards();
7069 let events = nodes[1].node.get_and_clear_pending_msg_events();
7070 assert_eq!(events.len(), 1);
7071 let (update_fail_htlc, commitment_signed) = match events[0] {
7072 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 } } => {
7073 assert!(update_add_htlcs.is_empty());
7074 assert!(update_fulfill_htlcs.is_empty());
7075 assert_eq!(update_fail_htlcs.len(), 1);
7076 assert!(update_fail_malformed_htlcs.is_empty());
7077 assert!(update_fee.is_none());
7078 (update_fail_htlcs[0].clone(), commitment_signed)
7080 _ => panic!("Unexpected event"),
7082 check_added_monitors!(nodes[1], 1);
7084 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7085 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7087 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7088 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7089 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7090 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7094 fn test_announce_disable_channels() {
7095 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7096 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7098 let chanmon_cfgs = create_chanmon_cfgs(2);
7099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7101 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7103 create_announced_chan_between_nodes(&nodes, 0, 1);
7104 create_announced_chan_between_nodes(&nodes, 1, 0);
7105 create_announced_chan_between_nodes(&nodes, 0, 1);
7108 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7109 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7111 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7112 nodes[0].node.timer_tick_occurred();
7114 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7115 assert_eq!(msg_events.len(), 3);
7116 let mut chans_disabled = HashMap::new();
7117 for e in msg_events {
7119 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7120 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7121 // Check that each channel gets updated exactly once
7122 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7123 panic!("Generated ChannelUpdate for wrong chan!");
7126 _ => panic!("Unexpected event"),
7130 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();
7131 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7132 assert_eq!(reestablish_1.len(), 3);
7133 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();
7134 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7135 assert_eq!(reestablish_2.len(), 3);
7137 // Reestablish chan_1
7138 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7139 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7140 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7141 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7142 // Reestablish chan_2
7143 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7144 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7145 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7146 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7147 // Reestablish chan_3
7148 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7149 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7150 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7151 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7153 for _ in 0..ENABLE_GOSSIP_TICKS {
7154 nodes[0].node.timer_tick_occurred();
7156 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7157 nodes[0].node.timer_tick_occurred();
7158 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7159 assert_eq!(msg_events.len(), 3);
7160 for e in msg_events {
7162 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7163 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7164 match chans_disabled.remove(&msg.contents.short_channel_id) {
7165 // Each update should have a higher timestamp than the previous one, replacing
7167 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7168 None => panic!("Generated ChannelUpdate for wrong chan!"),
7171 _ => panic!("Unexpected event"),
7174 // Check that each channel gets updated exactly once
7175 assert!(chans_disabled.is_empty());
7179 fn test_bump_penalty_txn_on_revoked_commitment() {
7180 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7181 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7183 let chanmon_cfgs = create_chanmon_cfgs(2);
7184 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7185 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7186 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7188 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7190 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7191 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7192 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7193 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7194 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7196 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7197 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7198 assert_eq!(revoked_txn[0].output.len(), 4);
7199 assert_eq!(revoked_txn[0].input.len(), 1);
7200 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7201 let revoked_txid = revoked_txn[0].txid();
7203 let mut penalty_sum = 0;
7204 for outp in revoked_txn[0].output.iter() {
7205 if outp.script_pubkey.is_v0_p2wsh() {
7206 penalty_sum += outp.value;
7210 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7211 let header_114 = connect_blocks(&nodes[1], 14);
7213 // Actually revoke tx by claiming a HTLC
7214 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7215 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7216 check_added_monitors!(nodes[1], 1);
7218 // One or more justice tx should have been broadcast, check it
7222 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7223 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7224 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7225 assert_eq!(node_txn[0].output.len(), 1);
7226 check_spends!(node_txn[0], revoked_txn[0]);
7227 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7228 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7229 penalty_1 = node_txn[0].txid();
7233 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7234 connect_blocks(&nodes[1], 15);
7235 let mut penalty_2 = penalty_1;
7236 let mut feerate_2 = 0;
7238 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7239 assert_eq!(node_txn.len(), 1);
7240 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7241 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7242 assert_eq!(node_txn[0].output.len(), 1);
7243 check_spends!(node_txn[0], revoked_txn[0]);
7244 penalty_2 = node_txn[0].txid();
7245 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7246 assert_ne!(penalty_2, penalty_1);
7247 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7248 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7249 // Verify 25% bump heuristic
7250 assert!(feerate_2 * 100 >= feerate_1 * 125);
7254 assert_ne!(feerate_2, 0);
7256 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7257 connect_blocks(&nodes[1], 1);
7259 let mut feerate_3 = 0;
7261 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7262 assert_eq!(node_txn.len(), 1);
7263 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7264 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7265 assert_eq!(node_txn[0].output.len(), 1);
7266 check_spends!(node_txn[0], revoked_txn[0]);
7267 penalty_3 = node_txn[0].txid();
7268 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7269 assert_ne!(penalty_3, penalty_2);
7270 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7271 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7272 // Verify 25% bump heuristic
7273 assert!(feerate_3 * 100 >= feerate_2 * 125);
7277 assert_ne!(feerate_3, 0);
7279 nodes[1].node.get_and_clear_pending_events();
7280 nodes[1].node.get_and_clear_pending_msg_events();
7284 fn test_bump_penalty_txn_on_revoked_htlcs() {
7285 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7286 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7288 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7289 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7290 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7291 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7292 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7294 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7295 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7296 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7297 let scorer = test_utils::TestScorer::new();
7298 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7299 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7300 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7301 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7302 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7303 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7304 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7305 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7307 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7308 assert_eq!(revoked_local_txn[0].input.len(), 1);
7309 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7311 // Revoke local commitment tx
7312 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7314 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7315 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7316 check_closed_broadcast!(nodes[1], true);
7317 check_added_monitors!(nodes[1], 1);
7318 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7319 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7321 let revoked_htlc_txn = {
7322 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7323 assert_eq!(txn.len(), 2);
7325 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7326 assert_eq!(txn[0].input.len(), 1);
7327 check_spends!(txn[0], revoked_local_txn[0]);
7329 assert_eq!(txn[1].input.len(), 1);
7330 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7331 assert_eq!(txn[1].output.len(), 1);
7332 check_spends!(txn[1], revoked_local_txn[0]);
7337 // Broadcast set of revoked txn on A
7338 let hash_128 = connect_blocks(&nodes[0], 40);
7339 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7340 connect_block(&nodes[0], &block_11);
7341 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7342 connect_block(&nodes[0], &block_129);
7343 let events = nodes[0].node.get_and_clear_pending_events();
7344 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7345 match events.last().unwrap() {
7346 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7347 _ => panic!("Unexpected event"),
7353 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7354 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7355 // Verify claim tx are spending revoked HTLC txn
7357 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7358 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7359 // which are included in the same block (they are broadcasted because we scan the
7360 // transactions linearly and generate claims as we go, they likely should be removed in the
7362 assert_eq!(node_txn[0].input.len(), 1);
7363 check_spends!(node_txn[0], revoked_local_txn[0]);
7364 assert_eq!(node_txn[1].input.len(), 1);
7365 check_spends!(node_txn[1], revoked_local_txn[0]);
7366 assert_eq!(node_txn[2].input.len(), 1);
7367 check_spends!(node_txn[2], revoked_local_txn[0]);
7369 // Each of the three justice transactions claim a separate (single) output of the three
7370 // available, which we check here:
7371 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7372 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7373 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7375 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7376 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7378 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7379 // output, checked above).
7380 assert_eq!(node_txn[3].input.len(), 2);
7381 assert_eq!(node_txn[3].output.len(), 1);
7382 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7384 first = node_txn[3].txid();
7385 // Store both feerates for later comparison
7386 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7387 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7388 penalty_txn = vec![node_txn[2].clone()];
7392 // Connect one more block to see if bumped penalty are issued for HTLC txn
7393 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7394 connect_block(&nodes[0], &block_130);
7395 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7396 connect_block(&nodes[0], &block_131);
7398 // Few more blocks to confirm penalty txn
7399 connect_blocks(&nodes[0], 4);
7400 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7401 let header_144 = connect_blocks(&nodes[0], 9);
7403 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7404 assert_eq!(node_txn.len(), 1);
7406 assert_eq!(node_txn[0].input.len(), 2);
7407 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7408 // Verify bumped tx is different and 25% bump heuristic
7409 assert_ne!(first, node_txn[0].txid());
7410 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7411 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7412 assert!(feerate_2 * 100 > feerate_1 * 125);
7413 let txn = vec![node_txn[0].clone()];
7417 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7418 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7419 connect_blocks(&nodes[0], 20);
7421 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7422 // We verify than no new transaction has been broadcast because previously
7423 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7424 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7425 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7426 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7427 // up bumped justice generation.
7428 assert_eq!(node_txn.len(), 0);
7431 check_closed_broadcast!(nodes[0], true);
7432 check_added_monitors!(nodes[0], 1);
7436 fn test_bump_penalty_txn_on_remote_commitment() {
7437 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7438 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7441 // Provide preimage for one
7442 // Check aggregation
7444 let chanmon_cfgs = create_chanmon_cfgs(2);
7445 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7446 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7447 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7449 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7450 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7451 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7453 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7454 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7455 assert_eq!(remote_txn[0].output.len(), 4);
7456 assert_eq!(remote_txn[0].input.len(), 1);
7457 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7459 // Claim a HTLC without revocation (provide B monitor with preimage)
7460 nodes[1].node.claim_funds(payment_preimage);
7461 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7462 mine_transaction(&nodes[1], &remote_txn[0]);
7463 check_added_monitors!(nodes[1], 2);
7464 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7466 // One or more claim tx should have been broadcast, check it
7470 let feerate_timeout;
7471 let feerate_preimage;
7473 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7474 // 3 transactions including:
7475 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7476 assert_eq!(node_txn.len(), 3);
7477 assert_eq!(node_txn[0].input.len(), 1);
7478 assert_eq!(node_txn[1].input.len(), 1);
7479 assert_eq!(node_txn[2].input.len(), 1);
7480 check_spends!(node_txn[0], remote_txn[0]);
7481 check_spends!(node_txn[1], remote_txn[0]);
7482 check_spends!(node_txn[2], remote_txn[0]);
7484 preimage = node_txn[0].txid();
7485 let index = node_txn[0].input[0].previous_output.vout;
7486 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7487 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7489 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7490 (node_txn[2].clone(), node_txn[1].clone())
7492 (node_txn[1].clone(), node_txn[2].clone())
7495 preimage_bump = preimage_bump_tx;
7496 check_spends!(preimage_bump, remote_txn[0]);
7497 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7499 timeout = timeout_tx.txid();
7500 let index = timeout_tx.input[0].previous_output.vout;
7501 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7502 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7506 assert_ne!(feerate_timeout, 0);
7507 assert_ne!(feerate_preimage, 0);
7509 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7510 connect_blocks(&nodes[1], 1);
7512 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7513 assert_eq!(node_txn.len(), 1);
7514 assert_eq!(node_txn[0].input.len(), 1);
7515 assert_eq!(preimage_bump.input.len(), 1);
7516 check_spends!(node_txn[0], remote_txn[0]);
7517 check_spends!(preimage_bump, remote_txn[0]);
7519 let index = preimage_bump.input[0].previous_output.vout;
7520 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7521 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7522 assert!(new_feerate * 100 > feerate_timeout * 125);
7523 assert_ne!(timeout, preimage_bump.txid());
7525 let index = node_txn[0].input[0].previous_output.vout;
7526 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7527 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7528 assert!(new_feerate * 100 > feerate_preimage * 125);
7529 assert_ne!(preimage, node_txn[0].txid());
7534 nodes[1].node.get_and_clear_pending_events();
7535 nodes[1].node.get_and_clear_pending_msg_events();
7539 fn test_counterparty_raa_skip_no_crash() {
7540 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7541 // commitment transaction, we would have happily carried on and provided them the next
7542 // commitment transaction based on one RAA forward. This would probably eventually have led to
7543 // channel closure, but it would not have resulted in funds loss. Still, our
7544 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7545 // check simply that the channel is closed in response to such an RAA, but don't check whether
7546 // we decide to punish our counterparty for revoking their funds (as we don't currently
7548 let chanmon_cfgs = create_chanmon_cfgs(2);
7549 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7550 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7551 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7552 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7554 let per_commitment_secret;
7555 let next_per_commitment_point;
7557 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7558 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7559 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7561 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7563 // Make signer believe we got a counterparty signature, so that it allows the revocation
7564 keys.get_enforcement_state().last_holder_commitment -= 1;
7565 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7567 // Must revoke without gaps
7568 keys.get_enforcement_state().last_holder_commitment -= 1;
7569 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7571 keys.get_enforcement_state().last_holder_commitment -= 1;
7572 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7573 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7576 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7577 &msgs::RevokeAndACK {
7579 per_commitment_secret,
7580 next_per_commitment_point,
7582 next_local_nonce: None,
7584 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7585 check_added_monitors!(nodes[1], 1);
7586 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7590 fn test_bump_txn_sanitize_tracking_maps() {
7591 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7592 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7594 let chanmon_cfgs = create_chanmon_cfgs(2);
7595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7597 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7599 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7600 // Lock HTLC in both directions
7601 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7602 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7604 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7605 assert_eq!(revoked_local_txn[0].input.len(), 1);
7606 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7608 // Revoke local commitment tx
7609 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7611 // Broadcast set of revoked txn on A
7612 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7613 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7614 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7616 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7617 check_closed_broadcast!(nodes[0], true);
7618 check_added_monitors!(nodes[0], 1);
7619 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7621 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7622 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7623 check_spends!(node_txn[0], revoked_local_txn[0]);
7624 check_spends!(node_txn[1], revoked_local_txn[0]);
7625 check_spends!(node_txn[2], revoked_local_txn[0]);
7626 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7630 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7631 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7633 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7634 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7635 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7640 fn test_channel_conf_timeout() {
7641 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7642 // confirm within 2016 blocks, as recommended by BOLT 2.
7643 let chanmon_cfgs = create_chanmon_cfgs(2);
7644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7646 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7648 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7650 // The outbound node should wait forever for confirmation:
7651 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7652 // copied here instead of directly referencing the constant.
7653 connect_blocks(&nodes[0], 2016);
7654 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7656 // The inbound node should fail the channel after exactly 2016 blocks
7657 connect_blocks(&nodes[1], 2015);
7658 check_added_monitors!(nodes[1], 0);
7659 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7661 connect_blocks(&nodes[1], 1);
7662 check_added_monitors!(nodes[1], 1);
7663 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7664 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7665 assert_eq!(close_ev.len(), 1);
7667 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7668 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7669 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7671 _ => panic!("Unexpected event"),
7676 fn test_override_channel_config() {
7677 let chanmon_cfgs = create_chanmon_cfgs(2);
7678 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7679 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7680 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7682 // Node0 initiates a channel to node1 using the override config.
7683 let mut override_config = UserConfig::default();
7684 override_config.channel_handshake_config.our_to_self_delay = 200;
7686 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7688 // Assert the channel created by node0 is using the override config.
7689 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7690 assert_eq!(res.channel_flags, 0);
7691 assert_eq!(res.to_self_delay, 200);
7695 fn test_override_0msat_htlc_minimum() {
7696 let mut zero_config = UserConfig::default();
7697 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7698 let chanmon_cfgs = create_chanmon_cfgs(2);
7699 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7700 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7701 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7703 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7704 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7705 assert_eq!(res.htlc_minimum_msat, 1);
7707 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7708 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7709 assert_eq!(res.htlc_minimum_msat, 1);
7713 fn test_channel_update_has_correct_htlc_maximum_msat() {
7714 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7715 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7716 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7717 // 90% of the `channel_value`.
7718 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7720 let mut config_30_percent = UserConfig::default();
7721 config_30_percent.channel_handshake_config.announced_channel = true;
7722 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7723 let mut config_50_percent = UserConfig::default();
7724 config_50_percent.channel_handshake_config.announced_channel = true;
7725 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7726 let mut config_95_percent = UserConfig::default();
7727 config_95_percent.channel_handshake_config.announced_channel = true;
7728 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7729 let mut config_100_percent = UserConfig::default();
7730 config_100_percent.channel_handshake_config.announced_channel = true;
7731 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7733 let chanmon_cfgs = create_chanmon_cfgs(4);
7734 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7735 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)]);
7736 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7738 let channel_value_satoshis = 100000;
7739 let channel_value_msat = channel_value_satoshis * 1000;
7740 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7741 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7742 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7744 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7745 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7747 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7748 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7749 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7750 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7751 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7752 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7754 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7755 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7757 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7758 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7759 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7761 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7765 fn test_manually_accept_inbound_channel_request() {
7766 let mut manually_accept_conf = UserConfig::default();
7767 manually_accept_conf.manually_accept_inbound_channels = true;
7768 let chanmon_cfgs = create_chanmon_cfgs(2);
7769 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7770 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7771 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7773 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7774 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7776 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7778 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7779 // accepting the inbound channel request.
7780 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7782 let events = nodes[1].node.get_and_clear_pending_events();
7784 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7785 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7787 _ => panic!("Unexpected event"),
7790 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7791 assert_eq!(accept_msg_ev.len(), 1);
7793 match accept_msg_ev[0] {
7794 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7795 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7797 _ => panic!("Unexpected event"),
7800 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7802 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7803 assert_eq!(close_msg_ev.len(), 1);
7805 let events = nodes[1].node.get_and_clear_pending_events();
7807 Event::ChannelClosed { user_channel_id, .. } => {
7808 assert_eq!(user_channel_id, 23);
7810 _ => panic!("Unexpected event"),
7815 fn test_manually_reject_inbound_channel_request() {
7816 let mut manually_accept_conf = UserConfig::default();
7817 manually_accept_conf.manually_accept_inbound_channels = true;
7818 let chanmon_cfgs = create_chanmon_cfgs(2);
7819 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7820 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7821 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7823 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7824 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7826 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7828 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7829 // rejecting the inbound channel request.
7830 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7832 let events = nodes[1].node.get_and_clear_pending_events();
7834 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7835 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7837 _ => panic!("Unexpected event"),
7840 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7841 assert_eq!(close_msg_ev.len(), 1);
7843 match close_msg_ev[0] {
7844 MessageSendEvent::HandleError { ref node_id, .. } => {
7845 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7847 _ => panic!("Unexpected event"),
7849 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7853 fn test_reject_funding_before_inbound_channel_accepted() {
7854 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7855 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7856 // the node operator before the counterparty sends a `FundingCreated` message. If a
7857 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7858 // and the channel should be closed.
7859 let mut manually_accept_conf = UserConfig::default();
7860 manually_accept_conf.manually_accept_inbound_channels = true;
7861 let chanmon_cfgs = create_chanmon_cfgs(2);
7862 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7863 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7864 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7866 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7867 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7868 let temp_channel_id = res.temporary_channel_id;
7870 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7872 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7873 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7875 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7876 nodes[1].node.get_and_clear_pending_events();
7878 // Get the `AcceptChannel` message of `nodes[1]` without calling
7879 // `ChannelManager::accept_inbound_channel`, which generates a
7880 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7881 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7882 // succeed when `nodes[0]` is passed to it.
7883 let accept_chan_msg = {
7884 let mut node_1_per_peer_lock;
7885 let mut node_1_peer_state_lock;
7886 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7887 channel.get_accept_channel_message()
7889 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7891 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7893 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7894 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7896 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7897 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7899 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7900 assert_eq!(close_msg_ev.len(), 1);
7902 let expected_err = "FundingCreated message received before the channel was accepted";
7903 match close_msg_ev[0] {
7904 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7905 assert_eq!(msg.channel_id, temp_channel_id);
7906 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7907 assert_eq!(msg.data, expected_err);
7909 _ => panic!("Unexpected event"),
7912 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7916 fn test_can_not_accept_inbound_channel_twice() {
7917 let mut manually_accept_conf = UserConfig::default();
7918 manually_accept_conf.manually_accept_inbound_channels = true;
7919 let chanmon_cfgs = create_chanmon_cfgs(2);
7920 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7921 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7922 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7924 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7925 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7927 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7929 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7930 // accepting the inbound channel request.
7931 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7933 let events = nodes[1].node.get_and_clear_pending_events();
7935 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7936 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7937 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7939 Err(APIError::APIMisuseError { err }) => {
7940 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7942 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7943 Err(_) => panic!("Unexpected Error"),
7946 _ => panic!("Unexpected event"),
7949 // Ensure that the channel wasn't closed after attempting to accept it twice.
7950 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7951 assert_eq!(accept_msg_ev.len(), 1);
7953 match accept_msg_ev[0] {
7954 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7955 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7957 _ => panic!("Unexpected event"),
7962 fn test_can_not_accept_unknown_inbound_channel() {
7963 let chanmon_cfg = create_chanmon_cfgs(2);
7964 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7965 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7966 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7968 let unknown_channel_id = [0; 32];
7969 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7971 Err(APIError::ChannelUnavailable { err }) => {
7972 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()));
7974 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7975 Err(_) => panic!("Unexpected Error"),
7980 fn test_onion_value_mpp_set_calculation() {
7981 // Test that we use the onion value `amt_to_forward` when
7982 // calculating whether we've reached the `total_msat` of an MPP
7983 // by having a routing node forward more than `amt_to_forward`
7984 // and checking that the receiving node doesn't generate
7985 // a PaymentClaimable event too early
7987 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7988 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7989 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7990 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7992 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7993 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7994 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7995 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7997 let total_msat = 100_000;
7998 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7999 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8000 let sample_path = route.paths.pop().unwrap();
8002 let mut path_1 = sample_path.clone();
8003 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8004 path_1.hops[0].short_channel_id = chan_1_id;
8005 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8006 path_1.hops[1].short_channel_id = chan_3_id;
8007 path_1.hops[1].fee_msat = 100_000;
8008 route.paths.push(path_1);
8010 let mut path_2 = sample_path.clone();
8011 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8012 path_2.hops[0].short_channel_id = chan_2_id;
8013 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8014 path_2.hops[1].short_channel_id = chan_4_id;
8015 path_2.hops[1].fee_msat = 1_000;
8016 route.paths.push(path_2);
8019 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8020 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8021 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8022 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8023 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8024 check_added_monitors!(nodes[0], expected_paths.len());
8026 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8027 assert_eq!(events.len(), expected_paths.len());
8030 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8031 let mut payment_event = SendEvent::from_event(ev);
8032 let mut prev_node = &nodes[0];
8034 for (idx, &node) in expected_paths[0].iter().enumerate() {
8035 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8037 if idx == 0 { // routing node
8038 let session_priv = [3; 32];
8039 let height = nodes[0].best_block_info().1;
8040 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8041 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8042 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8043 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8044 // Edit amt_to_forward to simulate the sender having set
8045 // the final amount and the routing node taking less fee
8046 onion_payloads[1].amt_to_forward = 99_000;
8047 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8048 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8051 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8052 check_added_monitors!(node, 0);
8053 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8054 expect_pending_htlcs_forwardable!(node);
8057 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8058 assert_eq!(events_2.len(), 1);
8059 check_added_monitors!(node, 1);
8060 payment_event = SendEvent::from_event(events_2.remove(0));
8061 assert_eq!(payment_event.msgs.len(), 1);
8063 let events_2 = node.node.get_and_clear_pending_events();
8064 assert!(events_2.is_empty());
8071 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8072 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8074 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8077 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8079 let routing_node_count = msat_amounts.len();
8080 let node_count = routing_node_count + 2;
8082 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8083 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8084 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8085 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8090 // Create channels for each amount
8091 let mut expected_paths = Vec::with_capacity(routing_node_count);
8092 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8093 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8094 for i in 0..routing_node_count {
8095 let routing_node = 2 + i;
8096 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8097 src_chan_ids.push(src_chan_id);
8098 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8099 dst_chan_ids.push(dst_chan_id);
8100 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8101 expected_paths.push(path);
8103 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8105 // Create a route for each amount
8106 let example_amount = 100000;
8107 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);
8108 let sample_path = route.paths.pop().unwrap();
8109 for i in 0..routing_node_count {
8110 let routing_node = 2 + i;
8111 let mut path = sample_path.clone();
8112 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8113 path.hops[0].short_channel_id = src_chan_ids[i];
8114 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8115 path.hops[1].short_channel_id = dst_chan_ids[i];
8116 path.hops[1].fee_msat = msat_amounts[i];
8117 route.paths.push(path);
8120 // Send payment with manually set total_msat
8121 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8122 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8123 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8124 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8125 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8126 check_added_monitors!(nodes[src_idx], expected_paths.len());
8128 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8129 assert_eq!(events.len(), expected_paths.len());
8130 let mut amount_received = 0;
8131 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8132 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8134 let current_path_amount = msat_amounts[path_idx];
8135 amount_received += current_path_amount;
8136 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8137 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8140 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8144 fn test_overshoot_mpp() {
8145 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8146 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8150 fn test_simple_mpp() {
8151 // Simple test of sending a multi-path payment.
8152 let chanmon_cfgs = create_chanmon_cfgs(4);
8153 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8154 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8155 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8157 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8158 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8159 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8160 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8162 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8163 let path = route.paths[0].clone();
8164 route.paths.push(path);
8165 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8166 route.paths[0].hops[0].short_channel_id = chan_1_id;
8167 route.paths[0].hops[1].short_channel_id = chan_3_id;
8168 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8169 route.paths[1].hops[0].short_channel_id = chan_2_id;
8170 route.paths[1].hops[1].short_channel_id = chan_4_id;
8171 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8172 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8176 fn test_preimage_storage() {
8177 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8178 let chanmon_cfgs = create_chanmon_cfgs(2);
8179 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8180 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8181 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8183 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8186 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8187 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8188 nodes[0].node.send_payment_with_route(&route, payment_hash,
8189 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8190 check_added_monitors!(nodes[0], 1);
8191 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8192 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8193 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8194 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8196 // Note that after leaving the above scope we have no knowledge of any arguments or return
8197 // values from previous calls.
8198 expect_pending_htlcs_forwardable!(nodes[1]);
8199 let events = nodes[1].node.get_and_clear_pending_events();
8200 assert_eq!(events.len(), 1);
8202 Event::PaymentClaimable { ref purpose, .. } => {
8204 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8205 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8207 _ => panic!("expected PaymentPurpose::InvoicePayment")
8210 _ => panic!("Unexpected event"),
8215 #[allow(deprecated)]
8216 fn test_secret_timeout() {
8217 // Simple test of payment secret storage time outs. After
8218 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8219 let chanmon_cfgs = create_chanmon_cfgs(2);
8220 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8221 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8222 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8224 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8226 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8228 // We should fail to register the same payment hash twice, at least until we've connected a
8229 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8230 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8231 assert_eq!(err, "Duplicate payment hash");
8232 } else { panic!(); }
8234 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8235 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8237 connect_block(&nodes[1], &block);
8238 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8239 assert_eq!(err, "Duplicate payment hash");
8240 } else { panic!(); }
8242 // If we then connect the second block, we should be able to register the same payment hash
8243 // again (this time getting a new payment secret).
8244 block.header.prev_blockhash = block.header.block_hash();
8245 block.header.time += 1;
8246 connect_block(&nodes[1], &block);
8247 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8248 assert_ne!(payment_secret_1, our_payment_secret);
8251 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8252 nodes[0].node.send_payment_with_route(&route, payment_hash,
8253 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8254 check_added_monitors!(nodes[0], 1);
8255 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8256 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8257 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8258 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8260 // Note that after leaving the above scope we have no knowledge of any arguments or return
8261 // values from previous calls.
8262 expect_pending_htlcs_forwardable!(nodes[1]);
8263 let events = nodes[1].node.get_and_clear_pending_events();
8264 assert_eq!(events.len(), 1);
8266 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8267 assert!(payment_preimage.is_none());
8268 assert_eq!(payment_secret, our_payment_secret);
8269 // We don't actually have the payment preimage with which to claim this payment!
8271 _ => panic!("Unexpected event"),
8276 fn test_bad_secret_hash() {
8277 // Simple test of unregistered payment hash/invalid payment secret handling
8278 let chanmon_cfgs = create_chanmon_cfgs(2);
8279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8281 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8283 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8285 let random_payment_hash = PaymentHash([42; 32]);
8286 let random_payment_secret = PaymentSecret([43; 32]);
8287 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8288 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8290 // All the below cases should end up being handled exactly identically, so we macro the
8291 // resulting events.
8292 macro_rules! handle_unknown_invalid_payment_data {
8293 ($payment_hash: expr) => {
8294 check_added_monitors!(nodes[0], 1);
8295 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8296 let payment_event = SendEvent::from_event(events.pop().unwrap());
8297 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8298 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8300 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8301 // again to process the pending backwards-failure of the HTLC
8302 expect_pending_htlcs_forwardable!(nodes[1]);
8303 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8304 check_added_monitors!(nodes[1], 1);
8306 // We should fail the payment back
8307 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8308 match events.pop().unwrap() {
8309 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8310 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8311 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8313 _ => panic!("Unexpected event"),
8318 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8319 // Error data is the HTLC value (100,000) and current block height
8320 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8322 // Send a payment with the right payment hash but the wrong payment secret
8323 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8324 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8325 handle_unknown_invalid_payment_data!(our_payment_hash);
8326 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8328 // Send a payment with a random payment hash, but the right payment secret
8329 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8330 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8331 handle_unknown_invalid_payment_data!(random_payment_hash);
8332 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8334 // Send a payment with a random payment hash and random payment secret
8335 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8336 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8337 handle_unknown_invalid_payment_data!(random_payment_hash);
8338 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8342 fn test_update_err_monitor_lockdown() {
8343 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8344 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8345 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8348 // This scenario may happen in a watchtower setup, where watchtower process a block height
8349 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8350 // commitment at same time.
8352 let chanmon_cfgs = create_chanmon_cfgs(2);
8353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8355 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8357 // Create some initial channel
8358 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8359 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8361 // Rebalance the network to generate htlc in the two directions
8362 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8364 // Route a HTLC from node 0 to node 1 (but don't settle)
8365 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8367 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8368 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8369 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8370 let persister = test_utils::TestPersister::new();
8373 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8374 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8375 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8376 assert!(new_monitor == *monitor);
8379 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);
8380 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8383 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8384 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8385 // transaction lock time requirements here.
8386 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8387 watchtower.chain_monitor.block_connected(&block, 200);
8389 // Try to update ChannelMonitor
8390 nodes[1].node.claim_funds(preimage);
8391 check_added_monitors!(nodes[1], 1);
8392 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8394 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8395 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8396 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8398 let mut node_0_per_peer_lock;
8399 let mut node_0_peer_state_lock;
8400 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8401 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8402 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8403 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8404 } else { assert!(false); }
8406 // Our local monitor is in-sync and hasn't processed yet timeout
8407 check_added_monitors!(nodes[0], 1);
8408 let events = nodes[0].node.get_and_clear_pending_events();
8409 assert_eq!(events.len(), 1);
8413 fn test_concurrent_monitor_claim() {
8414 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8415 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8416 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8417 // state N+1 confirms. Alice claims output from state N+1.
8419 let chanmon_cfgs = create_chanmon_cfgs(2);
8420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8422 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8424 // Create some initial channel
8425 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8426 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8428 // Rebalance the network to generate htlc in the two directions
8429 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8431 // Route a HTLC from node 0 to node 1 (but don't settle)
8432 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8434 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8435 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8436 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8437 let persister = test_utils::TestPersister::new();
8438 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8439 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8441 let watchtower_alice = {
8443 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8444 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8445 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8446 assert!(new_monitor == *monitor);
8449 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8450 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8453 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8454 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8455 // requirements here.
8456 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8457 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8458 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8460 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8462 let mut txn = alice_broadcaster.txn_broadcast();
8463 assert_eq!(txn.len(), 2);
8467 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8468 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8469 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8470 let persister = test_utils::TestPersister::new();
8471 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8472 let watchtower_bob = {
8474 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8475 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8476 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8477 assert!(new_monitor == *monitor);
8480 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8481 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8484 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8486 // Route another payment to generate another update with still previous HTLC pending
8487 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8488 nodes[1].node.send_payment_with_route(&route, payment_hash,
8489 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8490 check_added_monitors!(nodes[1], 1);
8492 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8493 assert_eq!(updates.update_add_htlcs.len(), 1);
8494 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8496 let mut node_0_per_peer_lock;
8497 let mut node_0_peer_state_lock;
8498 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8499 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8500 // Watchtower Alice should already have seen the block and reject the update
8501 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8502 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8503 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8504 } else { assert!(false); }
8506 // Our local monitor is in-sync and hasn't processed yet timeout
8507 check_added_monitors!(nodes[0], 1);
8509 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8510 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8512 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8515 let mut txn = bob_broadcaster.txn_broadcast();
8516 assert_eq!(txn.len(), 2);
8517 bob_state_y = txn.remove(0);
8520 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8521 let height = HTLC_TIMEOUT_BROADCAST + 1;
8522 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8523 check_closed_broadcast(&nodes[0], 1, true);
8524 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8525 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8526 check_added_monitors(&nodes[0], 1);
8528 let htlc_txn = alice_broadcaster.txn_broadcast();
8529 assert_eq!(htlc_txn.len(), 2);
8530 check_spends!(htlc_txn[0], bob_state_y);
8531 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8532 // it. However, she should, because it now has an invalid parent.
8533 check_spends!(htlc_txn[1], alice_state);
8538 fn test_pre_lockin_no_chan_closed_update() {
8539 // Test that if a peer closes a channel in response to a funding_created message we don't
8540 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8543 // Doing so would imply a channel monitor update before the initial channel monitor
8544 // registration, violating our API guarantees.
8546 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8547 // then opening a second channel with the same funding output as the first (which is not
8548 // rejected because the first channel does not exist in the ChannelManager) and closing it
8549 // before receiving funding_signed.
8550 let chanmon_cfgs = create_chanmon_cfgs(2);
8551 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8552 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8553 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8555 // Create an initial channel
8556 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8557 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8558 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8559 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8560 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8562 // Move the first channel through the funding flow...
8563 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8565 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8566 check_added_monitors!(nodes[0], 0);
8568 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8569 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8570 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8571 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8572 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8576 fn test_htlc_no_detection() {
8577 // This test is a mutation to underscore the detection logic bug we had
8578 // before #653. HTLC value routed is above the remaining balance, thus
8579 // inverting HTLC and `to_remote` output. HTLC will come second and
8580 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8581 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8582 // outputs order detection for correct spending children filtring.
8584 let chanmon_cfgs = create_chanmon_cfgs(2);
8585 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8586 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8587 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8589 // Create some initial channels
8590 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8592 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8593 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8594 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8595 assert_eq!(local_txn[0].input.len(), 1);
8596 assert_eq!(local_txn[0].output.len(), 3);
8597 check_spends!(local_txn[0], chan_1.3);
8599 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8600 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8601 connect_block(&nodes[0], &block);
8602 // We deliberately connect the local tx twice as this should provoke a failure calling
8603 // this test before #653 fix.
8604 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8605 check_closed_broadcast!(nodes[0], true);
8606 check_added_monitors!(nodes[0], 1);
8607 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8608 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8610 let htlc_timeout = {
8611 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8612 assert_eq!(node_txn.len(), 1);
8613 assert_eq!(node_txn[0].input.len(), 1);
8614 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8615 check_spends!(node_txn[0], local_txn[0]);
8619 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8620 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8621 expect_payment_failed!(nodes[0], our_payment_hash, false);
8624 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8625 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8626 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8627 // Carol, Alice would be the upstream node, and Carol the downstream.)
8629 // Steps of the test:
8630 // 1) Alice sends a HTLC to Carol through Bob.
8631 // 2) Carol doesn't settle the HTLC.
8632 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8633 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8634 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8635 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8636 // 5) Carol release the preimage to Bob off-chain.
8637 // 6) Bob claims the offered output on the broadcasted commitment.
8638 let chanmon_cfgs = create_chanmon_cfgs(3);
8639 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8640 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8641 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8643 // Create some initial channels
8644 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8645 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8647 // Steps (1) and (2):
8648 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8649 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8651 // Check that Alice's commitment transaction now contains an output for this HTLC.
8652 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8653 check_spends!(alice_txn[0], chan_ab.3);
8654 assert_eq!(alice_txn[0].output.len(), 2);
8655 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8656 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8657 assert_eq!(alice_txn.len(), 2);
8659 // Steps (3) and (4):
8660 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8661 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8662 let mut force_closing_node = 0; // Alice force-closes
8663 let mut counterparty_node = 1; // Bob if Alice force-closes
8666 if !broadcast_alice {
8667 force_closing_node = 1;
8668 counterparty_node = 0;
8670 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8671 check_closed_broadcast!(nodes[force_closing_node], true);
8672 check_added_monitors!(nodes[force_closing_node], 1);
8673 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8674 if go_onchain_before_fulfill {
8675 let txn_to_broadcast = match broadcast_alice {
8676 true => alice_txn.clone(),
8677 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8679 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8680 if broadcast_alice {
8681 check_closed_broadcast!(nodes[1], true);
8682 check_added_monitors!(nodes[1], 1);
8683 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8688 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8689 // process of removing the HTLC from their commitment transactions.
8690 nodes[2].node.claim_funds(payment_preimage);
8691 check_added_monitors!(nodes[2], 1);
8692 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8694 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8695 assert!(carol_updates.update_add_htlcs.is_empty());
8696 assert!(carol_updates.update_fail_htlcs.is_empty());
8697 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8698 assert!(carol_updates.update_fee.is_none());
8699 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8701 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8702 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8703 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8704 if !go_onchain_before_fulfill && broadcast_alice {
8705 let events = nodes[1].node.get_and_clear_pending_msg_events();
8706 assert_eq!(events.len(), 1);
8708 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8709 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8711 _ => panic!("Unexpected event"),
8714 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8715 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8716 // Carol<->Bob's updated commitment transaction info.
8717 check_added_monitors!(nodes[1], 2);
8719 let events = nodes[1].node.get_and_clear_pending_msg_events();
8720 assert_eq!(events.len(), 2);
8721 let bob_revocation = match events[0] {
8722 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8723 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8726 _ => panic!("Unexpected event"),
8728 let bob_updates = match events[1] {
8729 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8730 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8733 _ => panic!("Unexpected event"),
8736 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8737 check_added_monitors!(nodes[2], 1);
8738 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8739 check_added_monitors!(nodes[2], 1);
8741 let events = nodes[2].node.get_and_clear_pending_msg_events();
8742 assert_eq!(events.len(), 1);
8743 let carol_revocation = match events[0] {
8744 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8745 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8748 _ => panic!("Unexpected event"),
8750 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8751 check_added_monitors!(nodes[1], 1);
8753 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8754 // here's where we put said channel's commitment tx on-chain.
8755 let mut txn_to_broadcast = alice_txn.clone();
8756 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8757 if !go_onchain_before_fulfill {
8758 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8759 // If Bob was the one to force-close, he will have already passed these checks earlier.
8760 if broadcast_alice {
8761 check_closed_broadcast!(nodes[1], true);
8762 check_added_monitors!(nodes[1], 1);
8763 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8765 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8766 if broadcast_alice {
8767 assert_eq!(bob_txn.len(), 1);
8768 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8770 assert_eq!(bob_txn.len(), 2);
8771 check_spends!(bob_txn[0], chan_ab.3);
8776 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8777 // broadcasted commitment transaction.
8779 let script_weight = match broadcast_alice {
8780 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8781 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8783 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8784 // Bob force-closed and broadcasts the commitment transaction along with a
8785 // HTLC-output-claiming transaction.
8786 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8787 if broadcast_alice {
8788 assert_eq!(bob_txn.len(), 1);
8789 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8790 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8792 assert_eq!(bob_txn.len(), 2);
8793 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8794 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8800 fn test_onchain_htlc_settlement_after_close() {
8801 do_test_onchain_htlc_settlement_after_close(true, true);
8802 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8803 do_test_onchain_htlc_settlement_after_close(true, false);
8804 do_test_onchain_htlc_settlement_after_close(false, false);
8808 fn test_duplicate_temporary_channel_id_from_different_peers() {
8809 // Tests that we can accept two different `OpenChannel` requests with the same
8810 // `temporary_channel_id`, as long as they are from different peers.
8811 let chanmon_cfgs = create_chanmon_cfgs(3);
8812 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8813 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8814 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8816 // Create an first channel channel
8817 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8818 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8820 // Create an second channel
8821 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8822 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8824 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8825 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8826 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8828 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8829 // `temporary_channel_id` as they are from different peers.
8830 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8832 let events = nodes[0].node.get_and_clear_pending_msg_events();
8833 assert_eq!(events.len(), 1);
8835 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8836 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8837 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8839 _ => panic!("Unexpected event"),
8843 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8845 let events = nodes[0].node.get_and_clear_pending_msg_events();
8846 assert_eq!(events.len(), 1);
8848 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8849 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8850 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8852 _ => panic!("Unexpected event"),
8858 fn test_duplicate_chan_id() {
8859 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8860 // already open we reject it and keep the old channel.
8862 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8863 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8864 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8865 // updating logic for the existing channel.
8866 let chanmon_cfgs = create_chanmon_cfgs(2);
8867 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8868 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8869 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8871 // Create an initial channel
8872 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8873 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8874 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8875 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()));
8877 // Try to create a second channel with the same temporary_channel_id as the first and check
8878 // that it is rejected.
8879 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8881 let events = nodes[1].node.get_and_clear_pending_msg_events();
8882 assert_eq!(events.len(), 1);
8884 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8885 // Technically, at this point, nodes[1] would be justified in thinking both the
8886 // first (valid) and second (invalid) channels are closed, given they both have
8887 // the same non-temporary channel_id. However, currently we do not, so we just
8888 // move forward with it.
8889 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8890 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8892 _ => panic!("Unexpected event"),
8896 // Move the first channel through the funding flow...
8897 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8899 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8900 check_added_monitors!(nodes[0], 0);
8902 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8903 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8905 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8906 assert_eq!(added_monitors.len(), 1);
8907 assert_eq!(added_monitors[0].0, funding_output);
8908 added_monitors.clear();
8910 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8912 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8914 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8915 let channel_id = funding_outpoint.to_channel_id();
8917 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8920 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8921 // Technically this is allowed by the spec, but we don't support it and there's little reason
8922 // to. Still, it shouldn't cause any other issues.
8923 open_chan_msg.temporary_channel_id = channel_id;
8924 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8926 let events = nodes[1].node.get_and_clear_pending_msg_events();
8927 assert_eq!(events.len(), 1);
8929 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8930 // Technically, at this point, nodes[1] would be justified in thinking both
8931 // channels are closed, but currently we do not, so we just move forward with it.
8932 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8933 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8935 _ => panic!("Unexpected event"),
8939 // Now try to create a second channel which has a duplicate funding output.
8940 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8941 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8942 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8943 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()));
8944 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8946 let funding_created = {
8947 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8948 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8949 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8950 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8951 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8952 // channelmanager in a possibly nonsense state instead).
8953 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8954 let logger = test_utils::TestLogger::new();
8955 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8957 check_added_monitors!(nodes[0], 0);
8958 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8959 // At this point we'll look up if the channel_id is present and immediately fail the channel
8960 // without trying to persist the `ChannelMonitor`.
8961 check_added_monitors!(nodes[1], 0);
8963 // ...still, nodes[1] will reject the duplicate channel.
8965 let events = nodes[1].node.get_and_clear_pending_msg_events();
8966 assert_eq!(events.len(), 1);
8968 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8969 // Technically, at this point, nodes[1] would be justified in thinking both
8970 // channels are closed, but currently we do not, so we just move forward with it.
8971 assert_eq!(msg.channel_id, channel_id);
8972 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8974 _ => panic!("Unexpected event"),
8978 // finally, finish creating the original channel and send a payment over it to make sure
8979 // everything is functional.
8980 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8982 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8983 assert_eq!(added_monitors.len(), 1);
8984 assert_eq!(added_monitors[0].0, funding_output);
8985 added_monitors.clear();
8987 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8989 let events_4 = nodes[0].node.get_and_clear_pending_events();
8990 assert_eq!(events_4.len(), 0);
8991 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8992 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8994 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8995 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8996 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8998 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9002 fn test_error_chans_closed() {
9003 // Test that we properly handle error messages, closing appropriate channels.
9005 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9006 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9007 // we can test various edge cases around it to ensure we don't regress.
9008 let chanmon_cfgs = create_chanmon_cfgs(3);
9009 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9010 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9011 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9013 // Create some initial channels
9014 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9015 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9016 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9018 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9019 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9020 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9022 // Closing a channel from a different peer has no effect
9023 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9024 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9026 // Closing one channel doesn't impact others
9027 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9028 check_added_monitors!(nodes[0], 1);
9029 check_closed_broadcast!(nodes[0], false);
9030 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9031 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9032 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9033 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);
9034 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);
9036 // A null channel ID should close all channels
9037 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9038 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9039 check_added_monitors!(nodes[0], 2);
9040 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9041 let events = nodes[0].node.get_and_clear_pending_msg_events();
9042 assert_eq!(events.len(), 2);
9044 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9045 assert_eq!(msg.contents.flags & 2, 2);
9047 _ => panic!("Unexpected event"),
9050 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9051 assert_eq!(msg.contents.flags & 2, 2);
9053 _ => panic!("Unexpected event"),
9055 // Note that at this point users of a standard PeerHandler will end up calling
9056 // peer_disconnected.
9057 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9058 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9060 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9061 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9062 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9066 fn test_invalid_funding_tx() {
9067 // Test that we properly handle invalid funding transactions sent to us from a peer.
9069 // Previously, all other major lightning implementations had failed to properly sanitize
9070 // funding transactions from their counterparties, leading to a multi-implementation critical
9071 // security vulnerability (though we always sanitized properly, we've previously had
9072 // un-released crashes in the sanitization process).
9074 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9075 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9076 // gave up on it. We test this here by generating such a transaction.
9077 let chanmon_cfgs = create_chanmon_cfgs(2);
9078 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9079 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9080 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9082 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9083 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()));
9084 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()));
9086 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9088 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9089 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9090 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9092 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9093 let wit_program_script: Script = wit_program.into();
9094 for output in tx.output.iter_mut() {
9095 // Make the confirmed funding transaction have a bogus script_pubkey
9096 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9099 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9100 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()));
9101 check_added_monitors!(nodes[1], 1);
9102 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9104 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()));
9105 check_added_monitors!(nodes[0], 1);
9106 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9108 let events_1 = nodes[0].node.get_and_clear_pending_events();
9109 assert_eq!(events_1.len(), 0);
9111 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9112 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9113 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9115 let expected_err = "funding tx had wrong script/value or output index";
9116 confirm_transaction_at(&nodes[1], &tx, 1);
9117 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9118 check_added_monitors!(nodes[1], 1);
9119 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9120 assert_eq!(events_2.len(), 1);
9121 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9122 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9123 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9124 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9125 } else { panic!(); }
9126 } else { panic!(); }
9127 assert_eq!(nodes[1].node.list_channels().len(), 0);
9129 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9130 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9131 // as its not 32 bytes long.
9132 let mut spend_tx = Transaction {
9133 version: 2i32, lock_time: PackedLockTime::ZERO,
9134 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9135 previous_output: BitcoinOutPoint {
9139 script_sig: Script::new(),
9140 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9141 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9143 output: vec![TxOut {
9145 script_pubkey: Script::new(),
9148 check_spends!(spend_tx, tx);
9149 mine_transaction(&nodes[1], &spend_tx);
9152 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9153 // In the first version of the chain::Confirm interface, after a refactor was made to not
9154 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9155 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9156 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9157 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9158 // spending transaction until height N+1 (or greater). This was due to the way
9159 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9160 // spending transaction at the height the input transaction was confirmed at, not whether we
9161 // should broadcast a spending transaction at the current height.
9162 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9163 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9164 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9165 // until we learned about an additional block.
9167 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9168 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9169 let chanmon_cfgs = create_chanmon_cfgs(3);
9170 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9171 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9172 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9173 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9175 create_announced_chan_between_nodes(&nodes, 0, 1);
9176 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9177 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9178 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9179 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9181 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9182 check_closed_broadcast!(nodes[1], true);
9183 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9184 check_added_monitors!(nodes[1], 1);
9185 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9186 assert_eq!(node_txn.len(), 1);
9188 let conf_height = nodes[1].best_block_info().1;
9189 if !test_height_before_timelock {
9190 connect_blocks(&nodes[1], 24 * 6);
9192 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9193 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9194 if test_height_before_timelock {
9195 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9196 // generate any events or broadcast any transactions
9197 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9198 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9200 // We should broadcast an HTLC transaction spending our funding transaction first
9201 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9202 assert_eq!(spending_txn.len(), 2);
9203 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9204 check_spends!(spending_txn[1], node_txn[0]);
9205 // We should also generate a SpendableOutputs event with the to_self output (as its
9207 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9208 assert_eq!(descriptor_spend_txn.len(), 1);
9210 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9211 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9212 // additional block built on top of the current chain.
9213 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9214 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9215 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 }]);
9216 check_added_monitors!(nodes[1], 1);
9218 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9219 assert!(updates.update_add_htlcs.is_empty());
9220 assert!(updates.update_fulfill_htlcs.is_empty());
9221 assert_eq!(updates.update_fail_htlcs.len(), 1);
9222 assert!(updates.update_fail_malformed_htlcs.is_empty());
9223 assert!(updates.update_fee.is_none());
9224 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9225 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9226 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9231 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9232 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9233 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9236 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9237 let chanmon_cfgs = create_chanmon_cfgs(2);
9238 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9239 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9240 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9242 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9244 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9245 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9246 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9248 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9251 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9252 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9253 check_added_monitors!(nodes[0], 1);
9254 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9255 assert_eq!(events.len(), 1);
9256 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9257 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9258 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9260 expect_pending_htlcs_forwardable!(nodes[1]);
9261 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9264 // Note that we use a different PaymentId here to allow us to duplicativly pay
9265 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9266 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9267 check_added_monitors!(nodes[0], 1);
9268 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9269 assert_eq!(events.len(), 1);
9270 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9271 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9272 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9273 // At this point, nodes[1] would notice it has too much value for the payment. It will
9274 // assume the second is a privacy attack (no longer particularly relevant
9275 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9276 // the first HTLC delivered above.
9279 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9280 nodes[1].node.process_pending_htlc_forwards();
9282 if test_for_second_fail_panic {
9283 // Now we go fail back the first HTLC from the user end.
9284 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9286 let expected_destinations = vec![
9287 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9288 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9290 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9291 nodes[1].node.process_pending_htlc_forwards();
9293 check_added_monitors!(nodes[1], 1);
9294 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9295 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9297 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9298 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9299 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9301 let failure_events = nodes[0].node.get_and_clear_pending_events();
9302 assert_eq!(failure_events.len(), 4);
9303 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9304 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9305 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9306 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9308 // Let the second HTLC fail and claim the first
9309 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9310 nodes[1].node.process_pending_htlc_forwards();
9312 check_added_monitors!(nodes[1], 1);
9313 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9314 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9315 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9317 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9319 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9324 fn test_dup_htlc_second_fail_panic() {
9325 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9326 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9327 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9328 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9329 do_test_dup_htlc_second_rejected(true);
9333 fn test_dup_htlc_second_rejected() {
9334 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9335 // simply reject the second HTLC but are still able to claim the first HTLC.
9336 do_test_dup_htlc_second_rejected(false);
9340 fn test_inconsistent_mpp_params() {
9341 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9342 // such HTLC and allow the second to stay.
9343 let chanmon_cfgs = create_chanmon_cfgs(4);
9344 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9345 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9346 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9348 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9349 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9350 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9351 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9353 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9354 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9355 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9356 assert_eq!(route.paths.len(), 2);
9357 route.paths.sort_by(|path_a, _| {
9358 // Sort the path so that the path through nodes[1] comes first
9359 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9360 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9363 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9365 let cur_height = nodes[0].best_block_info().1;
9366 let payment_id = PaymentId([42; 32]);
9368 let session_privs = {
9369 // We create a fake route here so that we start with three pending HTLCs, which we'll
9370 // ultimately have, just not right away.
9371 let mut dup_route = route.clone();
9372 dup_route.paths.push(route.paths[1].clone());
9373 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9374 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9376 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9377 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9378 &None, session_privs[0]).unwrap();
9379 check_added_monitors!(nodes[0], 1);
9382 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9383 assert_eq!(events.len(), 1);
9384 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9386 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9388 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9389 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9390 check_added_monitors!(nodes[0], 1);
9393 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9394 assert_eq!(events.len(), 1);
9395 let payment_event = SendEvent::from_event(events.pop().unwrap());
9397 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9398 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9400 expect_pending_htlcs_forwardable!(nodes[2]);
9401 check_added_monitors!(nodes[2], 1);
9403 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9404 assert_eq!(events.len(), 1);
9405 let payment_event = SendEvent::from_event(events.pop().unwrap());
9407 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9408 check_added_monitors!(nodes[3], 0);
9409 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9411 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9412 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9413 // post-payment_secrets) and fail back the new HTLC.
9415 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9416 nodes[3].node.process_pending_htlc_forwards();
9417 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9418 nodes[3].node.process_pending_htlc_forwards();
9420 check_added_monitors!(nodes[3], 1);
9422 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9423 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9424 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9426 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 }]);
9427 check_added_monitors!(nodes[2], 1);
9429 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9430 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9431 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9433 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9435 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9436 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9437 &None, session_privs[2]).unwrap();
9438 check_added_monitors!(nodes[0], 1);
9440 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9441 assert_eq!(events.len(), 1);
9442 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9444 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9445 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9449 fn test_keysend_payments_to_public_node() {
9450 let chanmon_cfgs = create_chanmon_cfgs(2);
9451 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9452 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9453 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9455 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9456 let network_graph = nodes[0].network_graph.clone();
9457 let payer_pubkey = nodes[0].node.get_our_node_id();
9458 let payee_pubkey = nodes[1].node.get_our_node_id();
9459 let route_params = RouteParameters {
9460 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9461 final_value_msat: 10000,
9463 let scorer = test_utils::TestScorer::new();
9464 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9465 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9467 let test_preimage = PaymentPreimage([42; 32]);
9468 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9469 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9470 check_added_monitors!(nodes[0], 1);
9471 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9472 assert_eq!(events.len(), 1);
9473 let event = events.pop().unwrap();
9474 let path = vec![&nodes[1]];
9475 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9476 claim_payment(&nodes[0], &path, test_preimage);
9480 fn test_keysend_payments_to_private_node() {
9481 let chanmon_cfgs = create_chanmon_cfgs(2);
9482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9484 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9486 let payer_pubkey = nodes[0].node.get_our_node_id();
9487 let payee_pubkey = nodes[1].node.get_our_node_id();
9489 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9490 let route_params = RouteParameters {
9491 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9492 final_value_msat: 10000,
9494 let network_graph = nodes[0].network_graph.clone();
9495 let first_hops = nodes[0].node.list_usable_channels();
9496 let scorer = test_utils::TestScorer::new();
9497 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9498 let route = find_route(
9499 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9500 nodes[0].logger, &scorer, &(), &random_seed_bytes
9503 let test_preimage = PaymentPreimage([42; 32]);
9504 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9505 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9506 check_added_monitors!(nodes[0], 1);
9507 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9508 assert_eq!(events.len(), 1);
9509 let event = events.pop().unwrap();
9510 let path = vec![&nodes[1]];
9511 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9512 claim_payment(&nodes[0], &path, test_preimage);
9516 fn test_double_partial_claim() {
9517 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9518 // time out, the sender resends only some of the MPP parts, then the user processes the
9519 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9521 let chanmon_cfgs = create_chanmon_cfgs(4);
9522 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9523 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9524 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9526 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9527 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9528 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9529 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9531 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9532 assert_eq!(route.paths.len(), 2);
9533 route.paths.sort_by(|path_a, _| {
9534 // Sort the path so that the path through nodes[1] comes first
9535 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9536 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9539 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9540 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9541 // amount of time to respond to.
9543 // Connect some blocks to time out the payment
9544 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9545 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9547 let failed_destinations = vec![
9548 HTLCDestination::FailedPayment { payment_hash },
9549 HTLCDestination::FailedPayment { payment_hash },
9551 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9553 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9555 // nodes[1] now retries one of the two paths...
9556 nodes[0].node.send_payment_with_route(&route, payment_hash,
9557 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9558 check_added_monitors!(nodes[0], 2);
9560 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9561 assert_eq!(events.len(), 2);
9562 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9563 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9565 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9566 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9567 nodes[3].node.claim_funds(payment_preimage);
9568 check_added_monitors!(nodes[3], 0);
9569 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9572 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9573 #[derive(Clone, Copy, PartialEq)]
9574 enum ExposureEvent {
9575 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9577 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9579 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9580 AtUpdateFeeOutbound,
9583 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9584 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9587 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9588 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9589 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9590 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9591 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9592 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9593 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9594 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9596 let chanmon_cfgs = create_chanmon_cfgs(2);
9597 let mut config = test_default_channel_config();
9598 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9601 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9603 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9604 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9605 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9606 open_channel.max_accepted_htlcs = 60;
9608 open_channel.dust_limit_satoshis = 546;
9610 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9611 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9612 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9614 let opt_anchors = false;
9616 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9619 let mut node_0_per_peer_lock;
9620 let mut node_0_peer_state_lock;
9621 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9622 chan.holder_dust_limit_satoshis = 546;
9625 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9626 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()));
9627 check_added_monitors!(nodes[1], 1);
9628 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9630 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()));
9631 check_added_monitors!(nodes[0], 1);
9632 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9634 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9635 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9636 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9638 let dust_buffer_feerate = {
9639 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9640 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9641 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9642 chan.get_dust_buffer_feerate(None) as u64
9644 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;
9645 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9647 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;
9648 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9650 let dust_htlc_on_counterparty_tx: u64 = 25;
9651 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9654 if dust_outbound_balance {
9655 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9656 // Outbound dust balance: 4372 sats
9657 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9658 for _ in 0..dust_outbound_htlc_on_holder_tx {
9659 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9660 nodes[0].node.send_payment_with_route(&route, payment_hash,
9661 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9664 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9665 // Inbound dust balance: 4372 sats
9666 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9667 for _ in 0..dust_inbound_htlc_on_holder_tx {
9668 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9672 if dust_outbound_balance {
9673 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9674 // Outbound dust balance: 5000 sats
9675 for _ in 0..dust_htlc_on_counterparty_tx {
9676 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9677 nodes[0].node.send_payment_with_route(&route, payment_hash,
9678 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9681 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9682 // Inbound dust balance: 5000 sats
9683 for _ in 0..dust_htlc_on_counterparty_tx {
9684 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9689 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9690 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9691 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9692 let mut config = UserConfig::default();
9693 // With default dust exposure: 5000 sats
9695 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9696 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9697 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9698 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9699 ), true, APIError::ChannelUnavailable { ref err },
9700 assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9702 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9703 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9704 ), true, APIError::ChannelUnavailable { ref err },
9705 assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9707 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9708 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 });
9709 nodes[1].node.send_payment_with_route(&route, payment_hash,
9710 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9711 check_added_monitors!(nodes[1], 1);
9712 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9713 assert_eq!(events.len(), 1);
9714 let payment_event = SendEvent::from_event(events.remove(0));
9715 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9716 // With default dust exposure: 5000 sats
9718 // Outbound dust balance: 6399 sats
9719 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9720 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9721 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);
9723 // Outbound dust balance: 5200 sats
9724 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
9726 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9727 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9728 nodes[0].node.send_payment_with_route(&route, payment_hash,
9729 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9731 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9732 *feerate_lock = *feerate_lock * 10;
9734 nodes[0].node.timer_tick_occurred();
9735 check_added_monitors!(nodes[0], 1);
9736 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9739 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9740 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9741 added_monitors.clear();
9745 fn test_max_dust_htlc_exposure() {
9746 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9747 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9748 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9749 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9750 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9751 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9752 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9753 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9754 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9755 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9756 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9757 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9761 fn test_non_final_funding_tx() {
9762 let chanmon_cfgs = create_chanmon_cfgs(2);
9763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9765 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9767 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9768 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9769 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9770 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9771 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9773 let best_height = nodes[0].node.best_block.read().unwrap().height();
9775 let chan_id = *nodes[0].network_chan_count.borrow();
9776 let events = nodes[0].node.get_and_clear_pending_events();
9777 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9778 assert_eq!(events.len(), 1);
9779 let mut tx = match events[0] {
9780 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9781 // Timelock the transaction _beyond_ the best client height + 1.
9782 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9783 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9786 _ => panic!("Unexpected event"),
9788 // Transaction should fail as it's evaluated as non-final for propagation.
9789 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9790 Err(APIError::APIMisuseError { err }) => {
9791 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9796 // However, transaction should be accepted if it's in a +1 headroom from best block.
9797 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9798 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9799 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9803 fn accept_busted_but_better_fee() {
9804 // If a peer sends us a fee update that is too low, but higher than our previous channel
9805 // feerate, we should accept it. In the future we may want to consider closing the channel
9806 // later, but for now we only accept the update.
9807 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9808 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9809 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9810 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9812 create_chan_between_nodes(&nodes[0], &nodes[1]);
9814 // Set nodes[1] to expect 5,000 sat/kW.
9816 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9817 *feerate_lock = 5000;
9820 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9822 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9823 *feerate_lock = 1000;
9825 nodes[0].node.timer_tick_occurred();
9826 check_added_monitors!(nodes[0], 1);
9828 let events = nodes[0].node.get_and_clear_pending_msg_events();
9829 assert_eq!(events.len(), 1);
9831 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9832 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9833 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9835 _ => panic!("Unexpected event"),
9838 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9841 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9842 *feerate_lock = 2000;
9844 nodes[0].node.timer_tick_occurred();
9845 check_added_monitors!(nodes[0], 1);
9847 let events = nodes[0].node.get_and_clear_pending_msg_events();
9848 assert_eq!(events.len(), 1);
9850 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9851 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9852 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9854 _ => panic!("Unexpected event"),
9857 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9860 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9861 *feerate_lock = 1000;
9863 nodes[0].node.timer_tick_occurred();
9864 check_added_monitors!(nodes[0], 1);
9866 let events = nodes[0].node.get_and_clear_pending_msg_events();
9867 assert_eq!(events.len(), 1);
9869 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9870 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9871 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9872 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9873 check_closed_broadcast!(nodes[1], true);
9874 check_added_monitors!(nodes[1], 1);
9876 _ => panic!("Unexpected event"),
9880 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9881 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9882 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9883 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9884 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9885 let min_final_cltv_expiry_delta = 120;
9886 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9887 min_final_cltv_expiry_delta - 2 };
9888 let recv_value = 100_000;
9890 create_chan_between_nodes(&nodes[0], &nodes[1]);
9892 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9893 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9894 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9895 Some(recv_value), Some(min_final_cltv_expiry_delta));
9896 (payment_hash, payment_preimage, payment_secret)
9898 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9899 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9901 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9902 nodes[0].node.send_payment_with_route(&route, payment_hash,
9903 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9904 check_added_monitors!(nodes[0], 1);
9905 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9906 assert_eq!(events.len(), 1);
9907 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9908 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9909 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9910 expect_pending_htlcs_forwardable!(nodes[1]);
9913 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9914 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9916 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9918 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9920 check_added_monitors!(nodes[1], 1);
9922 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9923 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9924 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9926 expect_payment_failed!(nodes[0], payment_hash, true);
9931 fn test_payment_with_custom_min_cltv_expiry_delta() {
9932 do_payment_with_custom_min_final_cltv_expiry(false, false);
9933 do_payment_with_custom_min_final_cltv_expiry(false, true);
9934 do_payment_with_custom_min_final_cltv_expiry(true, false);
9935 do_payment_with_custom_min_final_cltv_expiry(true, true);