1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::UserConfig;
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92 assert_eq!(msg_events.len(), 1);
93 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96 &ErrorAction::SendErrorMessage { .. } => {
97 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99 _ => panic!("unexpected event!"),
101 } else { assert!(false); }
104 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106 // Test all mutations that would make the channel open message insane
107 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_funding_exceeds_no_wumbo_limit() {
127 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130 let chanmon_cfgs = create_chanmon_cfgs(2);
131 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180 let mut sender_node_per_peer_lock;
181 let mut sender_node_peer_state_lock;
182 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.context.holder_selected_channel_reserve_satoshis = 0;
184 chan.context.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 = 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.context.channel_transaction_parameters.as_counterparty_broadcastable()
733 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
736 let commit_signed_msg = msgs::CommitmentSigned {
739 htlc_signatures: res.1,
741 partial_signature_with_nonce: None,
744 let update_fee = msgs::UpdateFee {
746 feerate_per_kw: non_buffer_feerate + 4,
749 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
751 //While producing the commitment_signed response after handling a received update_fee request the
752 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753 //Should produce and error.
754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756 check_added_monitors!(nodes[1], 1);
757 check_closed_broadcast!(nodes[1], true);
758 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
762 fn test_update_fee_with_fundee_update_add_htlc() {
763 let chanmon_cfgs = create_chanmon_cfgs(2);
764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
770 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
773 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
776 nodes[0].node.timer_tick_occurred();
777 check_added_monitors!(nodes[0], 1);
779 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780 assert_eq!(events_0.len(), 1);
781 let (update_msg, commitment_signed) = match events_0[0] {
782 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
783 (update_fee.as_ref(), commitment_signed)
785 _ => panic!("Unexpected event"),
787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 check_added_monitors!(nodes[1], 1);
792 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
794 // nothing happens since node[1] is in AwaitingRemoteRevoke
795 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
796 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
798 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799 assert_eq!(added_monitors.len(), 0);
800 added_monitors.clear();
802 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804 // node[1] has nothing to do
806 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808 check_added_monitors!(nodes[0], 1);
810 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812 // No commitment_signed so get_event_msg's assert(len == 1) passes
813 check_added_monitors!(nodes[0], 1);
814 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815 check_added_monitors!(nodes[1], 1);
816 // AwaitingRemoteRevoke ends here
818 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823 assert_eq!(commitment_update.update_fee.is_none(), true);
825 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827 check_added_monitors!(nodes[0], 1);
828 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831 check_added_monitors!(nodes[1], 1);
832 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
834 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835 check_added_monitors!(nodes[1], 1);
836 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837 // No commitment_signed so get_event_msg's assert(len == 1) passes
839 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840 check_added_monitors!(nodes[0], 1);
841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
843 expect_pending_htlcs_forwardable!(nodes[0]);
845 let events = nodes[0].node.get_and_clear_pending_events();
846 assert_eq!(events.len(), 1);
848 Event::PaymentClaimable { .. } => { },
849 _ => panic!("Unexpected event"),
852 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
854 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
862 fn test_update_fee() {
863 let chanmon_cfgs = create_chanmon_cfgs(2);
864 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868 let channel_id = chan.2;
871 // (1) update_fee/commitment_signed ->
872 // <- (2) revoke_and_ack
873 // .- send (3) commitment_signed
874 // (4) update_fee/commitment_signed ->
875 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876 // <- (3) commitment_signed delivered
877 // send (6) revoke_and_ack -.
878 // <- (5) deliver revoke_and_ack
879 // (6) deliver revoke_and_ack ->
880 // .- send (7) commitment_signed in response to (4)
881 // <- (7) deliver commitment_signed
884 // Create and deliver (1)...
887 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888 feerate = *feerate_lock;
889 *feerate_lock = feerate + 20;
891 nodes[0].node.timer_tick_occurred();
892 check_added_monitors!(nodes[0], 1);
894 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895 assert_eq!(events_0.len(), 1);
896 let (update_msg, commitment_signed) = match events_0[0] {
897 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
898 (update_fee.as_ref(), commitment_signed)
900 _ => panic!("Unexpected event"),
902 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
904 // Generate (2) and (3):
905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907 check_added_monitors!(nodes[1], 1);
910 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912 check_added_monitors!(nodes[0], 1);
914 // Create and deliver (4)...
916 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917 *feerate_lock = feerate + 30;
919 nodes[0].node.timer_tick_occurred();
920 check_added_monitors!(nodes[0], 1);
921 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922 assert_eq!(events_0.len(), 1);
923 let (update_msg, commitment_signed) = match events_0[0] {
924 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
925 (update_fee.as_ref(), commitment_signed)
927 _ => panic!("Unexpected event"),
930 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932 check_added_monitors!(nodes[1], 1);
934 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935 // No commitment_signed so get_event_msg's assert(len == 1) passes
937 // Handle (3), creating (6):
938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939 check_added_monitors!(nodes[0], 1);
940 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941 // No commitment_signed so get_event_msg's assert(len == 1) passes
944 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946 check_added_monitors!(nodes[0], 1);
948 // Deliver (6), creating (7):
949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951 assert!(commitment_update.update_add_htlcs.is_empty());
952 assert!(commitment_update.update_fulfill_htlcs.is_empty());
953 assert!(commitment_update.update_fail_htlcs.is_empty());
954 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955 assert!(commitment_update.update_fee.is_none());
956 check_added_monitors!(nodes[1], 1);
959 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960 check_added_monitors!(nodes[0], 1);
961 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962 // No commitment_signed so get_event_msg's assert(len == 1) passes
964 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965 check_added_monitors!(nodes[1], 1);
966 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
968 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
976 fn fake_network_test() {
977 // Simple test which builds a network of ChannelManagers, connects them to each other, and
978 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979 let chanmon_cfgs = create_chanmon_cfgs(4);
980 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
984 // Create some initial channels
985 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
989 // Rebalance the network a bit by relaying one payment through all the channels...
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995 // Send some more payments
996 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1000 // Test failure packets
1001 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1004 // Add a new channel that skips 3
1005 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1007 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1009 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015 // Do some rebalance loop payments, simultaneously
1016 let mut hops = Vec::with_capacity(3);
1017 hops.push(RouteHop {
1018 pubkey: nodes[2].node.get_our_node_id(),
1019 node_features: NodeFeatures::empty(),
1020 short_channel_id: chan_2.0.contents.short_channel_id,
1021 channel_features: ChannelFeatures::empty(),
1023 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1025 hops.push(RouteHop {
1026 pubkey: nodes[3].node.get_our_node_id(),
1027 node_features: NodeFeatures::empty(),
1028 short_channel_id: chan_3.0.contents.short_channel_id,
1029 channel_features: ChannelFeatures::empty(),
1031 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1033 hops.push(RouteHop {
1034 pubkey: nodes[1].node.get_our_node_id(),
1035 node_features: nodes[1].node.node_features(),
1036 short_channel_id: chan_4.0.contents.short_channel_id,
1037 channel_features: nodes[1].node.channel_features(),
1039 cltv_expiry_delta: TEST_FINAL_CLTV,
1041 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1042 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1043 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1045 let mut hops = Vec::with_capacity(3);
1046 hops.push(RouteHop {
1047 pubkey: nodes[3].node.get_our_node_id(),
1048 node_features: NodeFeatures::empty(),
1049 short_channel_id: chan_4.0.contents.short_channel_id,
1050 channel_features: ChannelFeatures::empty(),
1052 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1054 hops.push(RouteHop {
1055 pubkey: nodes[2].node.get_our_node_id(),
1056 node_features: NodeFeatures::empty(),
1057 short_channel_id: chan_3.0.contents.short_channel_id,
1058 channel_features: ChannelFeatures::empty(),
1060 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1062 hops.push(RouteHop {
1063 pubkey: nodes[1].node.get_our_node_id(),
1064 node_features: nodes[1].node.node_features(),
1065 short_channel_id: chan_2.0.contents.short_channel_id,
1066 channel_features: nodes[1].node.channel_features(),
1068 cltv_expiry_delta: TEST_FINAL_CLTV,
1070 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1071 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1072 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1074 // Claim the rebalances...
1075 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1078 // Close down the channels...
1079 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 fn holding_cell_htlc_counting() {
1095 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097 // commitment dance rounds.
1098 let chanmon_cfgs = create_chanmon_cfgs(3);
1099 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102 create_announced_chan_between_nodes(&nodes, 0, 1);
1103 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1105 // Fetch a route in advance as we will be unable to once we're unable to send.
1106 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108 let mut payments = Vec::new();
1110 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111 nodes[1].node.send_payment_with_route(&route, payment_hash,
1112 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1113 payments.push((payment_preimage, payment_hash));
1115 check_added_monitors!(nodes[1], 1);
1117 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1118 assert_eq!(events.len(), 1);
1119 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1120 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1122 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1123 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1126 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1127 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1128 ), true, APIError::ChannelUnavailable { .. }, {});
1129 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1132 // This should also be true if we try to forward a payment.
1133 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1135 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1136 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1137 check_added_monitors!(nodes[0], 1);
1140 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141 assert_eq!(events.len(), 1);
1142 let payment_event = SendEvent::from_event(events.pop().unwrap());
1143 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148 // fails), the second will process the resulting failure and fail the HTLC backward.
1149 expect_pending_htlcs_forwardable!(nodes[1]);
1150 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1151 check_added_monitors!(nodes[1], 1);
1153 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1157 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1159 // Now forward all the pending HTLCs and claim them back
1160 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162 check_added_monitors!(nodes[2], 1);
1164 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166 check_added_monitors!(nodes[1], 1);
1167 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1169 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170 check_added_monitors!(nodes[1], 1);
1171 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1173 for ref update in as_updates.update_add_htlcs.iter() {
1174 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1176 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177 check_added_monitors!(nodes[2], 1);
1178 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179 check_added_monitors!(nodes[2], 1);
1180 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1182 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183 check_added_monitors!(nodes[1], 1);
1184 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185 check_added_monitors!(nodes[1], 1);
1186 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1188 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189 check_added_monitors!(nodes[2], 1);
1191 expect_pending_htlcs_forwardable!(nodes[2]);
1193 let events = nodes[2].node.get_and_clear_pending_events();
1194 assert_eq!(events.len(), payments.len());
1195 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1197 &Event::PaymentClaimable { ref payment_hash, .. } => {
1198 assert_eq!(*payment_hash, *hash);
1200 _ => panic!("Unexpected event"),
1204 for (preimage, _) in payments.drain(..) {
1205 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1208 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1212 fn duplicate_htlc_test() {
1213 // Test that we accept duplicate payment_hash HTLCs across the network and that
1214 // claiming/failing them are all separate and don't affect each other
1215 let chanmon_cfgs = create_chanmon_cfgs(6);
1216 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1220 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221 create_announced_chan_between_nodes(&nodes, 0, 3);
1222 create_announced_chan_between_nodes(&nodes, 1, 3);
1223 create_announced_chan_between_nodes(&nodes, 2, 3);
1224 create_announced_chan_between_nodes(&nodes, 3, 4);
1225 create_announced_chan_between_nodes(&nodes, 3, 5);
1227 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1229 *nodes[0].network_payment_count.borrow_mut() -= 1;
1230 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1232 *nodes[0].network_payment_count.borrow_mut() -= 1;
1233 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1235 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242 // Test that ChannelMonitor doesn't generate 2 preimage txn
1243 // when we have 2 HTLCs with same preimage that go across a node
1244 // in opposite directions, even with the same payment secret.
1245 let chanmon_cfgs = create_chanmon_cfgs(2);
1246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1250 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1253 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1255 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1257 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1259 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1261 // Provide preimage to node 0 by claiming payment
1262 nodes[0].node.claim_funds(payment_preimage);
1263 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264 check_added_monitors!(nodes[0], 1);
1266 // Broadcast node 1 commitment txn
1267 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1269 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270 let mut has_both_htlcs = 0; // check htlcs match ones committed
1271 for outp in remote_txn[0].output.iter() {
1272 if outp.value == 800_000 / 1000 {
1273 has_both_htlcs += 1;
1274 } else if outp.value == 900_000 / 1000 {
1275 has_both_htlcs += 1;
1278 assert_eq!(has_both_htlcs, 2);
1280 mine_transaction(&nodes[0], &remote_txn[0]);
1281 check_added_monitors!(nodes[0], 1);
1282 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1285 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286 assert_eq!(claim_txn.len(), 3);
1288 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289 check_spends!(claim_txn[1], remote_txn[0]);
1290 check_spends!(claim_txn[2], remote_txn[0]);
1291 let preimage_tx = &claim_txn[0];
1292 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1293 (&claim_txn[1], &claim_txn[2])
1295 (&claim_txn[2], &claim_txn[1])
1298 assert_eq!(preimage_tx.input.len(), 1);
1299 assert_eq!(preimage_bump_tx.input.len(), 1);
1301 assert_eq!(preimage_tx.input.len(), 1);
1302 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1303 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1305 assert_eq!(timeout_tx.input.len(), 1);
1306 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1307 check_spends!(timeout_tx, remote_txn[0]);
1308 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1310 let events = nodes[0].node.get_and_clear_pending_msg_events();
1311 assert_eq!(events.len(), 3);
1314 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1315 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1316 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1317 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1319 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1320 assert!(update_add_htlcs.is_empty());
1321 assert!(update_fail_htlcs.is_empty());
1322 assert_eq!(update_fulfill_htlcs.len(), 1);
1323 assert!(update_fail_malformed_htlcs.is_empty());
1324 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1326 _ => panic!("Unexpected event"),
1332 fn test_basic_channel_reserve() {
1333 let chanmon_cfgs = create_chanmon_cfgs(2);
1334 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1335 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1336 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1337 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1339 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1340 let channel_reserve = chan_stat.channel_reserve_msat;
1342 // The 2* and +1 are for the fee spike reserve.
1343 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1344 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1345 let (mut route, our_payment_hash, _, our_payment_secret) =
1346 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1347 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1348 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1349 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1351 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1352 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1353 else { panic!("Unexpected error variant"); }
1355 _ => panic!("Unexpected error variant"),
1357 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1359 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1363 fn test_fee_spike_violation_fails_htlc() {
1364 let chanmon_cfgs = create_chanmon_cfgs(2);
1365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1367 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1368 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1370 let (mut route, payment_hash, _, payment_secret) =
1371 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1372 route.paths[0].hops[0].fee_msat += 1;
1373 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1374 let secp_ctx = Secp256k1::new();
1375 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1377 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1379 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1380 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1381 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1382 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1383 let msg = msgs::UpdateAddHTLC {
1386 amount_msat: htlc_msat,
1387 payment_hash: payment_hash,
1388 cltv_expiry: htlc_cltv,
1389 onion_routing_packet: onion_packet,
1392 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1394 // Now manually create the commitment_signed message corresponding to the update_add
1395 // nodes[0] just sent. In the code for construction of this message, "local" refers
1396 // to the sender of the message, and "remote" refers to the receiver.
1398 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1400 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1402 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1403 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1404 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1405 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1406 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1407 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1408 let chan_signer = local_chan.get_signer();
1409 // Make the signer believe we validated another commitment, so we can release the secret
1410 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1412 let pubkeys = chan_signer.pubkeys();
1413 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1414 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1415 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1416 chan_signer.pubkeys().funding_pubkey)
1418 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1419 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1420 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1421 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1422 let chan_signer = remote_chan.get_signer();
1423 let pubkeys = chan_signer.pubkeys();
1424 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1425 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1426 chan_signer.pubkeys().funding_pubkey)
1429 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1430 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1431 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1433 // Build the remote commitment transaction so we can sign it, and then later use the
1434 // signature for the commitment_signed message.
1435 let local_chan_balance = 1313;
1437 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1439 amount_msat: 3460001,
1440 cltv_expiry: htlc_cltv,
1442 transaction_output_index: Some(1),
1445 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1448 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1449 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1450 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1451 let local_chan_signer = local_chan.get_signer();
1452 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1456 local_chan.context.opt_anchors(), local_funding, remote_funding,
1457 commit_tx_keys.clone(),
1459 &mut vec![(accepted_htlc_info, ())],
1460 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1462 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1465 let commit_signed_msg = msgs::CommitmentSigned {
1468 htlc_signatures: res.1,
1470 partial_signature_with_nonce: None,
1473 // Send the commitment_signed message to the nodes[1].
1474 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1475 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1477 // Send the RAA to nodes[1].
1478 let raa_msg = msgs::RevokeAndACK {
1480 per_commitment_secret: local_secret,
1481 next_per_commitment_point: next_local_point,
1483 next_local_nonce: None,
1485 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1487 let events = nodes[1].node.get_and_clear_pending_msg_events();
1488 assert_eq!(events.len(), 1);
1489 // Make sure the HTLC failed in the way we expect.
1491 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1492 assert_eq!(update_fail_htlcs.len(), 1);
1493 update_fail_htlcs[0].clone()
1495 _ => panic!("Unexpected event"),
1497 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1498 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1500 check_added_monitors!(nodes[1], 2);
1504 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1505 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1506 // Set the fee rate for the channel very high, to the point where the fundee
1507 // sending any above-dust amount would result in a channel reserve violation.
1508 // In this test we check that we would be prevented from sending an HTLC in
1510 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1513 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1514 let default_config = UserConfig::default();
1515 let opt_anchors = false;
1517 let mut push_amt = 100_000_000;
1518 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1520 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1522 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1524 // Fetch a route in advance as we will be unable to once we're unable to send.
1525 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1526 // Sending exactly enough to hit the reserve amount should be accepted
1527 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1528 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1531 // However one more HTLC should be significantly over the reserve amount and fail.
1532 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1533 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1534 ), true, APIError::ChannelUnavailable { .. }, {});
1535 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1539 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1540 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1541 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1544 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1545 let default_config = UserConfig::default();
1546 let opt_anchors = false;
1548 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1549 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1550 // transaction fee with 0 HTLCs (183 sats)).
1551 let mut push_amt = 100_000_000;
1552 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1553 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1554 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1556 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1557 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1558 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1561 let (mut route, payment_hash, _, payment_secret) =
1562 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1563 route.paths[0].hops[0].fee_msat = 700_000;
1564 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1565 let secp_ctx = Secp256k1::new();
1566 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1567 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1568 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1569 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1570 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1571 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1572 let msg = msgs::UpdateAddHTLC {
1574 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1575 amount_msat: htlc_msat,
1576 payment_hash: payment_hash,
1577 cltv_expiry: htlc_cltv,
1578 onion_routing_packet: onion_packet,
1581 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1582 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1583 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1584 assert_eq!(nodes[0].node.list_channels().len(), 0);
1585 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1586 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1587 check_added_monitors!(nodes[0], 1);
1588 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1592 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1593 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1594 // calculating our commitment transaction fee (this was previously broken).
1595 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1596 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1600 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1601 let default_config = UserConfig::default();
1602 let opt_anchors = false;
1604 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1605 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1606 // transaction fee with 0 HTLCs (183 sats)).
1607 let mut push_amt = 100_000_000;
1608 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1609 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1610 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1612 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1613 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1614 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1615 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1616 // commitment transaction fee.
1617 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1619 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1620 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1621 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1624 // One more than the dust amt should fail, however.
1625 let (mut route, our_payment_hash, _, our_payment_secret) =
1626 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1627 route.paths[0].hops[0].fee_msat += 1;
1628 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1629 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1630 ), true, APIError::ChannelUnavailable { .. }, {});
1634 fn test_chan_init_feerate_unaffordability() {
1635 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1636 // channel reserve and feerate requirements.
1637 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1638 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1641 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1642 let default_config = UserConfig::default();
1643 let opt_anchors = false;
1645 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1647 let mut push_amt = 100_000_000;
1648 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1649 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1650 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1652 // During open, we don't have a "counterparty channel reserve" to check against, so that
1653 // requirement only comes into play on the open_channel handling side.
1654 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1655 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1656 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1657 open_channel_msg.push_msat += 1;
1658 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1660 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1661 assert_eq!(msg_events.len(), 1);
1662 match msg_events[0] {
1663 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1664 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1666 _ => panic!("Unexpected event"),
1671 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1672 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1673 // calculating our counterparty's commitment transaction fee (this was previously broken).
1674 let chanmon_cfgs = create_chanmon_cfgs(2);
1675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1677 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1678 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1680 let payment_amt = 46000; // Dust amount
1681 // In the previous code, these first four payments would succeed.
1682 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1695 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1696 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1697 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1702 let chanmon_cfgs = create_chanmon_cfgs(3);
1703 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1704 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1705 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1706 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1707 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1710 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1711 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1712 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1713 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1715 // Add a 2* and +1 for the fee spike reserve.
1716 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1717 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1718 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1720 // Add a pending HTLC.
1721 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1722 let payment_event_1 = {
1723 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1724 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1725 check_added_monitors!(nodes[0], 1);
1727 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1728 assert_eq!(events.len(), 1);
1729 SendEvent::from_event(events.remove(0))
1731 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1733 // Attempt to trigger a channel reserve violation --> payment failure.
1734 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1735 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1736 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1737 let mut route_2 = route_1.clone();
1738 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1740 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1741 let secp_ctx = Secp256k1::new();
1742 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1743 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1744 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1745 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1746 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1747 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1748 let msg = msgs::UpdateAddHTLC {
1751 amount_msat: htlc_msat + 1,
1752 payment_hash: our_payment_hash_1,
1753 cltv_expiry: htlc_cltv,
1754 onion_routing_packet: onion_packet,
1757 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1758 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1759 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1760 assert_eq!(nodes[1].node.list_channels().len(), 1);
1761 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1762 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1763 check_added_monitors!(nodes[1], 1);
1764 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1768 fn test_inbound_outbound_capacity_is_not_zero() {
1769 let chanmon_cfgs = create_chanmon_cfgs(2);
1770 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1771 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1772 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1773 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1774 let channels0 = node_chanmgrs[0].list_channels();
1775 let channels1 = node_chanmgrs[1].list_channels();
1776 let default_config = UserConfig::default();
1777 assert_eq!(channels0.len(), 1);
1778 assert_eq!(channels1.len(), 1);
1780 let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1781 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1782 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1784 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1785 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1788 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1789 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1793 fn test_channel_reserve_holding_cell_htlcs() {
1794 let chanmon_cfgs = create_chanmon_cfgs(3);
1795 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1796 // When this test was written, the default base fee floated based on the HTLC count.
1797 // It is now fixed, so we simply set the fee to the expected value here.
1798 let mut config = test_default_channel_config();
1799 config.channel_config.forwarding_fee_base_msat = 239;
1800 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1801 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1802 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1803 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1805 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1806 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1808 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1809 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1811 macro_rules! expect_forward {
1813 let mut events = $node.node.get_and_clear_pending_msg_events();
1814 assert_eq!(events.len(), 1);
1815 check_added_monitors!($node, 1);
1816 let payment_event = SendEvent::from_event(events.remove(0));
1821 let feemsat = 239; // set above
1822 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1823 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1824 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1826 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1828 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1830 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1831 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1832 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1833 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1834 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1836 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1837 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1838 ), true, APIError::ChannelUnavailable { .. }, {});
1839 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1842 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1843 // nodes[0]'s wealth
1845 let amt_msat = recv_value_0 + total_fee_msat;
1846 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1847 // Also, ensure that each payment has enough to be over the dust limit to
1848 // ensure it'll be included in each commit tx fee calculation.
1849 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1850 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1851 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1855 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1856 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1857 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1858 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1859 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1861 let (stat01_, stat11_, stat12_, stat22_) = (
1862 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1863 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1864 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1865 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1868 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1869 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1870 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1871 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1872 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1875 // adding pending output.
1876 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1877 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1878 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1879 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1880 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1881 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1882 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1883 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1884 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1886 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1887 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1888 let amt_msat_1 = recv_value_1 + total_fee_msat;
1890 let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1891 let payment_event_1 = {
1892 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1893 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1894 check_added_monitors!(nodes[0], 1);
1896 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1897 assert_eq!(events.len(), 1);
1898 SendEvent::from_event(events.remove(0))
1900 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1902 // channel reserve test with htlc pending output > 0
1903 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1905 let mut route = route_1.clone();
1906 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1907 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1908 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1909 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1910 ), true, APIError::ChannelUnavailable { .. }, {});
1911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1914 // split the rest to test holding cell
1915 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1916 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1917 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1918 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1920 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1921 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1924 // now see if they go through on both sides
1925 let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1926 // but this will stuck in the holding cell
1927 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1928 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1929 check_added_monitors!(nodes[0], 0);
1930 let events = nodes[0].node.get_and_clear_pending_events();
1931 assert_eq!(events.len(), 0);
1933 // test with outbound holding cell amount > 0
1935 let (mut route, our_payment_hash, _, our_payment_secret) =
1936 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1937 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1938 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1939 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1940 ), true, APIError::ChannelUnavailable { .. }, {});
1941 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1944 let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1945 // this will also stuck in the holding cell
1946 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1947 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1948 check_added_monitors!(nodes[0], 0);
1949 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1950 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1952 // flush the pending htlc
1953 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1954 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1955 check_added_monitors!(nodes[1], 1);
1957 // the pending htlc should be promoted to committed
1958 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1959 check_added_monitors!(nodes[0], 1);
1960 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1962 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1963 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1964 // No commitment_signed so get_event_msg's assert(len == 1) passes
1965 check_added_monitors!(nodes[0], 1);
1967 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1968 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1969 check_added_monitors!(nodes[1], 1);
1971 expect_pending_htlcs_forwardable!(nodes[1]);
1973 let ref payment_event_11 = expect_forward!(nodes[1]);
1974 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1975 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1977 expect_pending_htlcs_forwardable!(nodes[2]);
1978 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1980 // flush the htlcs in the holding cell
1981 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1982 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1984 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1985 expect_pending_htlcs_forwardable!(nodes[1]);
1987 let ref payment_event_3 = expect_forward!(nodes[1]);
1988 assert_eq!(payment_event_3.msgs.len(), 2);
1989 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1990 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1992 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1993 expect_pending_htlcs_forwardable!(nodes[2]);
1995 let events = nodes[2].node.get_and_clear_pending_events();
1996 assert_eq!(events.len(), 2);
1998 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
1999 assert_eq!(our_payment_hash_21, *payment_hash);
2000 assert_eq!(recv_value_21, amount_msat);
2001 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2002 assert_eq!(via_channel_id, Some(chan_2.2));
2004 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2005 assert!(payment_preimage.is_none());
2006 assert_eq!(our_payment_secret_21, *payment_secret);
2008 _ => panic!("expected PaymentPurpose::InvoicePayment")
2011 _ => panic!("Unexpected event"),
2014 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2015 assert_eq!(our_payment_hash_22, *payment_hash);
2016 assert_eq!(recv_value_22, amount_msat);
2017 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2018 assert_eq!(via_channel_id, Some(chan_2.2));
2020 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2021 assert!(payment_preimage.is_none());
2022 assert_eq!(our_payment_secret_22, *payment_secret);
2024 _ => panic!("expected PaymentPurpose::InvoicePayment")
2027 _ => panic!("Unexpected event"),
2030 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2031 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2032 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2034 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2035 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2036 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2038 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2039 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2040 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2041 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2042 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2044 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2045 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2049 fn channel_reserve_in_flight_removes() {
2050 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2051 // can send to its counterparty, but due to update ordering, the other side may not yet have
2052 // considered those HTLCs fully removed.
2053 // This tests that we don't count HTLCs which will not be included in the next remote
2054 // commitment transaction towards the reserve value (as it implies no commitment transaction
2055 // will be generated which violates the remote reserve value).
2056 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2058 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2059 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2060 // you only consider the value of the first HTLC, it may not),
2061 // * start routing a third HTLC from A to B,
2062 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2063 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2064 // * deliver the first fulfill from B
2065 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2067 // * deliver A's response CS and RAA.
2068 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2069 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2070 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2071 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2072 let chanmon_cfgs = create_chanmon_cfgs(2);
2073 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2074 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2075 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2076 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2078 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2079 // Route the first two HTLCs.
2080 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2081 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2082 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2084 // Start routing the third HTLC (this is just used to get everyone in the right state).
2085 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2087 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2088 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2089 check_added_monitors!(nodes[0], 1);
2090 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2091 assert_eq!(events.len(), 1);
2092 SendEvent::from_event(events.remove(0))
2095 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2096 // initial fulfill/CS.
2097 nodes[1].node.claim_funds(payment_preimage_1);
2098 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2099 check_added_monitors!(nodes[1], 1);
2100 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2102 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2103 // remove the second HTLC when we send the HTLC back from B to A.
2104 nodes[1].node.claim_funds(payment_preimage_2);
2105 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2106 check_added_monitors!(nodes[1], 1);
2107 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2109 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2110 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2111 check_added_monitors!(nodes[0], 1);
2112 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2113 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2115 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2116 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2117 check_added_monitors!(nodes[1], 1);
2118 // B is already AwaitingRAA, so cant generate a CS here
2119 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2121 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2122 check_added_monitors!(nodes[1], 1);
2123 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2125 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2126 check_added_monitors!(nodes[0], 1);
2127 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2129 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2130 check_added_monitors!(nodes[1], 1);
2131 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2133 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2134 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2135 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2136 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2137 // on-chain as necessary).
2138 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2139 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2140 check_added_monitors!(nodes[0], 1);
2141 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2142 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2144 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2145 check_added_monitors!(nodes[1], 1);
2146 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2148 expect_pending_htlcs_forwardable!(nodes[1]);
2149 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2151 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2152 // resolve the second HTLC from A's point of view.
2153 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2154 check_added_monitors!(nodes[0], 1);
2155 expect_payment_path_successful!(nodes[0]);
2156 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2158 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2159 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2160 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2162 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2163 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2164 check_added_monitors!(nodes[1], 1);
2165 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2166 assert_eq!(events.len(), 1);
2167 SendEvent::from_event(events.remove(0))
2170 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2171 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2172 check_added_monitors!(nodes[0], 1);
2173 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2175 // Now just resolve all the outstanding messages/HTLCs for completeness...
2177 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2178 check_added_monitors!(nodes[1], 1);
2179 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2181 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2182 check_added_monitors!(nodes[1], 1);
2184 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2185 check_added_monitors!(nodes[0], 1);
2186 expect_payment_path_successful!(nodes[0]);
2187 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2189 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2190 check_added_monitors!(nodes[1], 1);
2191 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2193 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2194 check_added_monitors!(nodes[0], 1);
2196 expect_pending_htlcs_forwardable!(nodes[0]);
2197 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2199 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2200 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2204 fn channel_monitor_network_test() {
2205 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2206 // tests that ChannelMonitor is able to recover from various states.
2207 let chanmon_cfgs = create_chanmon_cfgs(5);
2208 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2209 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2210 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2212 // Create some initial channels
2213 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2214 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2215 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2216 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2218 // Make sure all nodes are at the same starting height
2219 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2220 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2221 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2222 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2223 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2225 // Rebalance the network a bit by relaying one payment through all the channels...
2226 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2227 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2228 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2229 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2231 // Simple case with no pending HTLCs:
2232 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2233 check_added_monitors!(nodes[1], 1);
2234 check_closed_broadcast!(nodes[1], true);
2236 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2237 assert_eq!(node_txn.len(), 1);
2238 mine_transaction(&nodes[0], &node_txn[0]);
2239 check_added_monitors!(nodes[0], 1);
2240 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2242 check_closed_broadcast!(nodes[0], true);
2243 assert_eq!(nodes[0].node.list_channels().len(), 0);
2244 assert_eq!(nodes[1].node.list_channels().len(), 1);
2245 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2246 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2248 // One pending HTLC is discarded by the force-close:
2249 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2251 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2252 // broadcasted until we reach the timelock time).
2253 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2254 check_closed_broadcast!(nodes[1], true);
2255 check_added_monitors!(nodes[1], 1);
2257 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2258 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2259 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2260 mine_transaction(&nodes[2], &node_txn[0]);
2261 check_added_monitors!(nodes[2], 1);
2262 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2264 check_closed_broadcast!(nodes[2], true);
2265 assert_eq!(nodes[1].node.list_channels().len(), 0);
2266 assert_eq!(nodes[2].node.list_channels().len(), 1);
2267 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2268 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2270 macro_rules! claim_funds {
2271 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2273 $node.node.claim_funds($preimage);
2274 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2275 check_added_monitors!($node, 1);
2277 let events = $node.node.get_and_clear_pending_msg_events();
2278 assert_eq!(events.len(), 1);
2280 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2281 assert!(update_add_htlcs.is_empty());
2282 assert!(update_fail_htlcs.is_empty());
2283 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2285 _ => panic!("Unexpected event"),
2291 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2292 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2293 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2294 check_added_monitors!(nodes[2], 1);
2295 check_closed_broadcast!(nodes[2], true);
2296 let node2_commitment_txid;
2298 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2299 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2300 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2301 node2_commitment_txid = node_txn[0].txid();
2303 // Claim the payment on nodes[3], giving it knowledge of the preimage
2304 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2305 mine_transaction(&nodes[3], &node_txn[0]);
2306 check_added_monitors!(nodes[3], 1);
2307 check_preimage_claim(&nodes[3], &node_txn);
2309 check_closed_broadcast!(nodes[3], true);
2310 assert_eq!(nodes[2].node.list_channels().len(), 0);
2311 assert_eq!(nodes[3].node.list_channels().len(), 1);
2312 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2313 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2315 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2316 // confusing us in the following tests.
2317 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2319 // One pending HTLC to time out:
2320 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2321 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2324 let (close_chan_update_1, close_chan_update_2) = {
2325 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2326 let events = nodes[3].node.get_and_clear_pending_msg_events();
2327 assert_eq!(events.len(), 2);
2328 let close_chan_update_1 = match events[0] {
2329 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2332 _ => panic!("Unexpected event"),
2335 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2336 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2338 _ => panic!("Unexpected event"),
2340 check_added_monitors!(nodes[3], 1);
2342 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2344 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2345 node_txn.retain(|tx| {
2346 if tx.input[0].previous_output.txid == node2_commitment_txid {
2352 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2354 // Claim the payment on nodes[4], giving it knowledge of the preimage
2355 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2357 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2358 let events = nodes[4].node.get_and_clear_pending_msg_events();
2359 assert_eq!(events.len(), 2);
2360 let close_chan_update_2 = match events[0] {
2361 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2364 _ => panic!("Unexpected event"),
2367 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2368 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2370 _ => panic!("Unexpected event"),
2372 check_added_monitors!(nodes[4], 1);
2373 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2375 mine_transaction(&nodes[4], &node_txn[0]);
2376 check_preimage_claim(&nodes[4], &node_txn);
2377 (close_chan_update_1, close_chan_update_2)
2379 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2380 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2381 assert_eq!(nodes[3].node.list_channels().len(), 0);
2382 assert_eq!(nodes[4].node.list_channels().len(), 0);
2384 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2385 ChannelMonitorUpdateStatus::Completed);
2386 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2387 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2391 fn test_justice_tx_htlc_timeout() {
2392 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2393 let mut alice_config = UserConfig::default();
2394 alice_config.channel_handshake_config.announced_channel = true;
2395 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2396 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2397 let mut bob_config = UserConfig::default();
2398 bob_config.channel_handshake_config.announced_channel = true;
2399 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2400 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2401 let user_cfgs = [Some(alice_config), Some(bob_config)];
2402 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2403 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2404 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2407 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2408 // Create some new channels:
2409 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2411 // A pending HTLC which will be revoked:
2412 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2413 // Get the will-be-revoked local txn from nodes[0]
2414 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2415 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2416 assert_eq!(revoked_local_txn[0].input.len(), 1);
2417 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2418 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2419 assert_eq!(revoked_local_txn[1].input.len(), 1);
2420 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2421 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2422 // Revoke the old state
2423 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2426 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2428 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2430 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2431 check_spends!(node_txn[0], revoked_local_txn[0]);
2432 node_txn.swap_remove(0);
2434 check_added_monitors!(nodes[1], 1);
2435 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2436 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2438 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2439 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2440 // Verify broadcast of revoked HTLC-timeout
2441 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2442 check_added_monitors!(nodes[0], 1);
2443 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2444 // Broadcast revoked HTLC-timeout on node 1
2445 mine_transaction(&nodes[1], &node_txn[1]);
2446 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2448 get_announce_close_broadcast_events(&nodes, 0, 1);
2449 assert_eq!(nodes[0].node.list_channels().len(), 0);
2450 assert_eq!(nodes[1].node.list_channels().len(), 0);
2454 fn test_justice_tx_htlc_success() {
2455 // Test justice txn built on revoked HTLC-Success tx, against both sides
2456 let mut alice_config = UserConfig::default();
2457 alice_config.channel_handshake_config.announced_channel = true;
2458 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2459 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2460 let mut bob_config = UserConfig::default();
2461 bob_config.channel_handshake_config.announced_channel = true;
2462 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2463 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2464 let user_cfgs = [Some(alice_config), Some(bob_config)];
2465 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2466 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2467 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2470 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2471 // Create some new channels:
2472 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2474 // A pending HTLC which will be revoked:
2475 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2476 // Get the will-be-revoked local txn from B
2477 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2478 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2479 assert_eq!(revoked_local_txn[0].input.len(), 1);
2480 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2481 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2482 // Revoke the old state
2483 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2485 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2487 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2488 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2489 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2491 check_spends!(node_txn[0], revoked_local_txn[0]);
2492 node_txn.swap_remove(0);
2494 check_added_monitors!(nodes[0], 1);
2495 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2497 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2498 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2499 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2500 check_added_monitors!(nodes[1], 1);
2501 mine_transaction(&nodes[0], &node_txn[1]);
2502 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2503 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2505 get_announce_close_broadcast_events(&nodes, 0, 1);
2506 assert_eq!(nodes[0].node.list_channels().len(), 0);
2507 assert_eq!(nodes[1].node.list_channels().len(), 0);
2511 fn revoked_output_claim() {
2512 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2513 // transaction is broadcast by its counterparty
2514 let chanmon_cfgs = create_chanmon_cfgs(2);
2515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2518 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2519 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2520 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2521 assert_eq!(revoked_local_txn.len(), 1);
2522 // Only output is the full channel value back to nodes[0]:
2523 assert_eq!(revoked_local_txn[0].output.len(), 1);
2524 // Send a payment through, updating everyone's latest commitment txn
2525 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2527 // Inform nodes[1] that nodes[0] broadcast a stale tx
2528 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2529 check_added_monitors!(nodes[1], 1);
2530 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2531 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2532 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2534 check_spends!(node_txn[0], revoked_local_txn[0]);
2536 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2537 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2538 get_announce_close_broadcast_events(&nodes, 0, 1);
2539 check_added_monitors!(nodes[0], 1);
2540 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2544 fn claim_htlc_outputs_shared_tx() {
2545 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2546 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2547 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2550 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2552 // Create some new channel:
2553 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2555 // Rebalance the network to generate htlc in the two directions
2556 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2557 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2558 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2559 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2561 // Get the will-be-revoked local txn from node[0]
2562 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2563 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2564 assert_eq!(revoked_local_txn[0].input.len(), 1);
2565 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2566 assert_eq!(revoked_local_txn[1].input.len(), 1);
2567 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2568 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2569 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2571 //Revoke the old state
2572 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2575 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2576 check_added_monitors!(nodes[0], 1);
2577 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2578 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2579 check_added_monitors!(nodes[1], 1);
2580 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2581 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2582 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2584 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2585 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2587 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2588 check_spends!(node_txn[0], revoked_local_txn[0]);
2590 let mut witness_lens = BTreeSet::new();
2591 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2592 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2593 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2594 assert_eq!(witness_lens.len(), 3);
2595 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2596 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2597 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2599 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2600 // ANTI_REORG_DELAY confirmations.
2601 mine_transaction(&nodes[1], &node_txn[0]);
2602 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2603 expect_payment_failed!(nodes[1], payment_hash_2, false);
2605 get_announce_close_broadcast_events(&nodes, 0, 1);
2606 assert_eq!(nodes[0].node.list_channels().len(), 0);
2607 assert_eq!(nodes[1].node.list_channels().len(), 0);
2611 fn claim_htlc_outputs_single_tx() {
2612 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2613 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2614 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2615 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2616 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2617 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2619 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2621 // Rebalance the network to generate htlc in the two directions
2622 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2623 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2624 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2625 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2626 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2628 // Get the will-be-revoked local txn from node[0]
2629 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2631 //Revoke the old state
2632 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2635 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2636 check_added_monitors!(nodes[0], 1);
2637 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2638 check_added_monitors!(nodes[1], 1);
2639 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2640 let mut events = nodes[0].node.get_and_clear_pending_events();
2641 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2642 match events.last().unwrap() {
2643 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2644 _ => panic!("Unexpected event"),
2647 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2648 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2650 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2652 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2653 assert_eq!(node_txn[0].input.len(), 1);
2654 check_spends!(node_txn[0], chan_1.3);
2655 assert_eq!(node_txn[1].input.len(), 1);
2656 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2657 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2658 check_spends!(node_txn[1], node_txn[0]);
2660 // Filter out any non justice transactions.
2661 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2662 assert!(node_txn.len() > 3);
2664 assert_eq!(node_txn[0].input.len(), 1);
2665 assert_eq!(node_txn[1].input.len(), 1);
2666 assert_eq!(node_txn[2].input.len(), 1);
2668 check_spends!(node_txn[0], revoked_local_txn[0]);
2669 check_spends!(node_txn[1], revoked_local_txn[0]);
2670 check_spends!(node_txn[2], revoked_local_txn[0]);
2672 let mut witness_lens = BTreeSet::new();
2673 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2674 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2675 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2676 assert_eq!(witness_lens.len(), 3);
2677 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2678 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2679 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2681 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2682 // ANTI_REORG_DELAY confirmations.
2683 mine_transaction(&nodes[1], &node_txn[0]);
2684 mine_transaction(&nodes[1], &node_txn[1]);
2685 mine_transaction(&nodes[1], &node_txn[2]);
2686 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2687 expect_payment_failed!(nodes[1], payment_hash_2, false);
2689 get_announce_close_broadcast_events(&nodes, 0, 1);
2690 assert_eq!(nodes[0].node.list_channels().len(), 0);
2691 assert_eq!(nodes[1].node.list_channels().len(), 0);
2695 fn test_htlc_on_chain_success() {
2696 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2697 // the preimage backward accordingly. So here we test that ChannelManager is
2698 // broadcasting the right event to other nodes in payment path.
2699 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2700 // A --------------------> B ----------------------> C (preimage)
2701 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2702 // commitment transaction was broadcast.
2703 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2705 // B should be able to claim via preimage if A then broadcasts its local tx.
2706 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2707 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2708 // PaymentSent event).
2710 let chanmon_cfgs = create_chanmon_cfgs(3);
2711 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2712 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2713 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2715 // Create some initial channels
2716 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2717 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2719 // Ensure all nodes are at the same height
2720 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2721 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2722 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2723 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2725 // Rebalance the network a bit by relaying one payment through all the channels...
2726 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2727 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2729 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2730 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2732 // Broadcast legit commitment tx from C on B's chain
2733 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2734 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2735 assert_eq!(commitment_tx.len(), 1);
2736 check_spends!(commitment_tx[0], chan_2.3);
2737 nodes[2].node.claim_funds(our_payment_preimage);
2738 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2739 nodes[2].node.claim_funds(our_payment_preimage_2);
2740 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2741 check_added_monitors!(nodes[2], 2);
2742 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2743 assert!(updates.update_add_htlcs.is_empty());
2744 assert!(updates.update_fail_htlcs.is_empty());
2745 assert!(updates.update_fail_malformed_htlcs.is_empty());
2746 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2748 mine_transaction(&nodes[2], &commitment_tx[0]);
2749 check_closed_broadcast!(nodes[2], true);
2750 check_added_monitors!(nodes[2], 1);
2751 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2752 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2753 assert_eq!(node_txn.len(), 2);
2754 check_spends!(node_txn[0], commitment_tx[0]);
2755 check_spends!(node_txn[1], commitment_tx[0]);
2756 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2757 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2758 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2759 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2760 assert_eq!(node_txn[0].lock_time.0, 0);
2761 assert_eq!(node_txn[1].lock_time.0, 0);
2763 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2764 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2765 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2767 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2768 assert_eq!(added_monitors.len(), 1);
2769 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2770 added_monitors.clear();
2772 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2773 assert_eq!(forwarded_events.len(), 3);
2774 match forwarded_events[0] {
2775 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2776 _ => panic!("Unexpected event"),
2778 let chan_id = Some(chan_1.2);
2779 match forwarded_events[1] {
2780 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2781 assert_eq!(fee_earned_msat, Some(1000));
2782 assert_eq!(prev_channel_id, chan_id);
2783 assert_eq!(claim_from_onchain_tx, true);
2784 assert_eq!(next_channel_id, Some(chan_2.2));
2785 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2789 match forwarded_events[2] {
2790 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2791 assert_eq!(fee_earned_msat, Some(1000));
2792 assert_eq!(prev_channel_id, chan_id);
2793 assert_eq!(claim_from_onchain_tx, true);
2794 assert_eq!(next_channel_id, Some(chan_2.2));
2795 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2799 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2801 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2802 assert_eq!(added_monitors.len(), 2);
2803 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2804 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2805 added_monitors.clear();
2807 assert_eq!(events.len(), 3);
2809 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2810 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2812 match nodes_2_event {
2813 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2814 _ => panic!("Unexpected event"),
2817 match nodes_0_event {
2818 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2819 assert!(update_add_htlcs.is_empty());
2820 assert!(update_fail_htlcs.is_empty());
2821 assert_eq!(update_fulfill_htlcs.len(), 1);
2822 assert!(update_fail_malformed_htlcs.is_empty());
2823 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2825 _ => panic!("Unexpected event"),
2828 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2830 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2831 _ => panic!("Unexpected event"),
2834 macro_rules! check_tx_local_broadcast {
2835 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2836 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2837 assert_eq!(node_txn.len(), 2);
2838 // Node[1]: 2 * HTLC-timeout tx
2839 // Node[0]: 2 * HTLC-timeout tx
2840 check_spends!(node_txn[0], $commitment_tx);
2841 check_spends!(node_txn[1], $commitment_tx);
2842 assert_ne!(node_txn[0].lock_time.0, 0);
2843 assert_ne!(node_txn[1].lock_time.0, 0);
2845 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2846 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2847 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2848 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2850 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2851 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2852 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2853 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2858 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2859 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2861 // Broadcast legit commitment tx from A on B's chain
2862 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2863 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2864 check_spends!(node_a_commitment_tx[0], chan_1.3);
2865 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2866 check_closed_broadcast!(nodes[1], true);
2867 check_added_monitors!(nodes[1], 1);
2868 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2869 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2870 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2871 let commitment_spend =
2872 if node_txn.len() == 1 {
2875 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2876 // FullBlockViaListen
2877 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2878 check_spends!(node_txn[1], commitment_tx[0]);
2879 check_spends!(node_txn[2], commitment_tx[0]);
2880 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2883 check_spends!(node_txn[0], commitment_tx[0]);
2884 check_spends!(node_txn[1], commitment_tx[0]);
2885 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2890 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2891 assert_eq!(commitment_spend.input.len(), 2);
2892 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2893 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2894 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2895 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2896 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2897 // we already checked the same situation with A.
2899 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2900 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2901 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2902 check_closed_broadcast!(nodes[0], true);
2903 check_added_monitors!(nodes[0], 1);
2904 let events = nodes[0].node.get_and_clear_pending_events();
2905 assert_eq!(events.len(), 5);
2906 let mut first_claimed = false;
2907 for event in events {
2909 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2910 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2911 assert!(!first_claimed);
2912 first_claimed = true;
2914 assert_eq!(payment_preimage, our_payment_preimage_2);
2915 assert_eq!(payment_hash, payment_hash_2);
2918 Event::PaymentPathSuccessful { .. } => {},
2919 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2920 _ => panic!("Unexpected event"),
2923 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2926 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2927 // Test that in case of a unilateral close onchain, we detect the state of output and
2928 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2929 // broadcasting the right event to other nodes in payment path.
2930 // A ------------------> B ----------------------> C (timeout)
2931 // B's commitment tx C's commitment tx
2933 // B's HTLC timeout tx B's timeout tx
2935 let chanmon_cfgs = create_chanmon_cfgs(3);
2936 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2937 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2938 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2939 *nodes[0].connect_style.borrow_mut() = connect_style;
2940 *nodes[1].connect_style.borrow_mut() = connect_style;
2941 *nodes[2].connect_style.borrow_mut() = connect_style;
2943 // Create some intial channels
2944 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2945 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2947 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2948 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2949 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2951 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2953 // Broadcast legit commitment tx from C on B's chain
2954 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2955 check_spends!(commitment_tx[0], chan_2.3);
2956 nodes[2].node.fail_htlc_backwards(&payment_hash);
2957 check_added_monitors!(nodes[2], 0);
2958 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2959 check_added_monitors!(nodes[2], 1);
2961 let events = nodes[2].node.get_and_clear_pending_msg_events();
2962 assert_eq!(events.len(), 1);
2964 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2965 assert!(update_add_htlcs.is_empty());
2966 assert!(!update_fail_htlcs.is_empty());
2967 assert!(update_fulfill_htlcs.is_empty());
2968 assert!(update_fail_malformed_htlcs.is_empty());
2969 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2971 _ => panic!("Unexpected event"),
2973 mine_transaction(&nodes[2], &commitment_tx[0]);
2974 check_closed_broadcast!(nodes[2], true);
2975 check_added_monitors!(nodes[2], 1);
2976 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2977 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2978 assert_eq!(node_txn.len(), 0);
2980 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2981 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2982 mine_transaction(&nodes[1], &commitment_tx[0]);
2983 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2984 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2986 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2987 if nodes[1].connect_style.borrow().skips_blocks() {
2988 assert_eq!(txn.len(), 1);
2990 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2992 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
2993 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2997 mine_transaction(&nodes[1], &timeout_tx);
2998 check_added_monitors!(nodes[1], 1);
2999 check_closed_broadcast!(nodes[1], true);
3001 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3003 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3004 check_added_monitors!(nodes[1], 1);
3005 let events = nodes[1].node.get_and_clear_pending_msg_events();
3006 assert_eq!(events.len(), 1);
3008 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3009 assert!(update_add_htlcs.is_empty());
3010 assert!(!update_fail_htlcs.is_empty());
3011 assert!(update_fulfill_htlcs.is_empty());
3012 assert!(update_fail_malformed_htlcs.is_empty());
3013 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3015 _ => panic!("Unexpected event"),
3018 // Broadcast legit commitment tx from B on A's chain
3019 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3020 check_spends!(commitment_tx[0], chan_1.3);
3022 mine_transaction(&nodes[0], &commitment_tx[0]);
3023 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3025 check_closed_broadcast!(nodes[0], true);
3026 check_added_monitors!(nodes[0], 1);
3027 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3028 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3029 assert_eq!(node_txn.len(), 1);
3030 check_spends!(node_txn[0], commitment_tx[0]);
3031 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3035 fn test_htlc_on_chain_timeout() {
3036 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3037 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3038 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3042 fn test_simple_commitment_revoked_fail_backward() {
3043 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3044 // and fail backward accordingly.
3046 let chanmon_cfgs = create_chanmon_cfgs(3);
3047 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3048 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3049 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3051 // Create some initial channels
3052 create_announced_chan_between_nodes(&nodes, 0, 1);
3053 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3055 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3056 // Get the will-be-revoked local txn from nodes[2]
3057 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3058 // Revoke the old state
3059 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3061 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3063 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3064 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3065 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3066 check_added_monitors!(nodes[1], 1);
3067 check_closed_broadcast!(nodes[1], true);
3069 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3070 check_added_monitors!(nodes[1], 1);
3071 let events = nodes[1].node.get_and_clear_pending_msg_events();
3072 assert_eq!(events.len(), 1);
3074 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3075 assert!(update_add_htlcs.is_empty());
3076 assert_eq!(update_fail_htlcs.len(), 1);
3077 assert!(update_fulfill_htlcs.is_empty());
3078 assert!(update_fail_malformed_htlcs.is_empty());
3079 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3081 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3082 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3083 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3085 _ => panic!("Unexpected event"),
3089 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3090 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3091 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3092 // commitment transaction anymore.
3093 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3094 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3095 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3096 // technically disallowed and we should probably handle it reasonably.
3097 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3098 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3100 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3101 // commitment_signed (implying it will be in the latest remote commitment transaction).
3102 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3103 // and once they revoke the previous commitment transaction (allowing us to send a new
3104 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3105 let chanmon_cfgs = create_chanmon_cfgs(3);
3106 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3107 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3108 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3110 // Create some initial channels
3111 create_announced_chan_between_nodes(&nodes, 0, 1);
3112 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3114 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3115 // Get the will-be-revoked local txn from nodes[2]
3116 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3117 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3118 // Revoke the old state
3119 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3121 let value = if use_dust {
3122 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3123 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3124 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3125 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3128 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3129 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3132 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3133 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3134 check_added_monitors!(nodes[2], 1);
3135 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3136 assert!(updates.update_add_htlcs.is_empty());
3137 assert!(updates.update_fulfill_htlcs.is_empty());
3138 assert!(updates.update_fail_malformed_htlcs.is_empty());
3139 assert_eq!(updates.update_fail_htlcs.len(), 1);
3140 assert!(updates.update_fee.is_none());
3141 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3142 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3143 // Drop the last RAA from 3 -> 2
3145 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3146 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3147 check_added_monitors!(nodes[2], 1);
3148 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3149 assert!(updates.update_add_htlcs.is_empty());
3150 assert!(updates.update_fulfill_htlcs.is_empty());
3151 assert!(updates.update_fail_malformed_htlcs.is_empty());
3152 assert_eq!(updates.update_fail_htlcs.len(), 1);
3153 assert!(updates.update_fee.is_none());
3154 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3155 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3156 check_added_monitors!(nodes[1], 1);
3157 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3158 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3159 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3160 check_added_monitors!(nodes[2], 1);
3162 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3163 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3164 check_added_monitors!(nodes[2], 1);
3165 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3166 assert!(updates.update_add_htlcs.is_empty());
3167 assert!(updates.update_fulfill_htlcs.is_empty());
3168 assert!(updates.update_fail_malformed_htlcs.is_empty());
3169 assert_eq!(updates.update_fail_htlcs.len(), 1);
3170 assert!(updates.update_fee.is_none());
3171 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3172 // At this point first_payment_hash has dropped out of the latest two commitment
3173 // transactions that nodes[1] is tracking...
3174 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3175 check_added_monitors!(nodes[1], 1);
3176 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3177 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3178 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3179 check_added_monitors!(nodes[2], 1);
3181 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3182 // on nodes[2]'s RAA.
3183 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3184 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3185 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3186 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3187 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3188 check_added_monitors!(nodes[1], 0);
3191 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3192 // One monitor for the new revocation preimage, no second on as we won't generate a new
3193 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3194 check_added_monitors!(nodes[1], 1);
3195 let events = nodes[1].node.get_and_clear_pending_events();
3196 assert_eq!(events.len(), 2);
3198 Event::PendingHTLCsForwardable { .. } => { },
3199 _ => panic!("Unexpected event"),
3202 Event::HTLCHandlingFailed { .. } => { },
3203 _ => panic!("Unexpected event"),
3205 // Deliberately don't process the pending fail-back so they all fail back at once after
3206 // block connection just like the !deliver_bs_raa case
3209 let mut failed_htlcs = HashSet::new();
3210 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3212 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3213 check_added_monitors!(nodes[1], 1);
3214 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3216 let events = nodes[1].node.get_and_clear_pending_events();
3217 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3219 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3220 _ => panic!("Unexepected event"),
3223 Event::PaymentPathFailed { ref payment_hash, .. } => {
3224 assert_eq!(*payment_hash, fourth_payment_hash);
3226 _ => panic!("Unexpected event"),
3229 Event::PaymentFailed { ref payment_hash, .. } => {
3230 assert_eq!(*payment_hash, fourth_payment_hash);
3232 _ => panic!("Unexpected event"),
3235 nodes[1].node.process_pending_htlc_forwards();
3236 check_added_monitors!(nodes[1], 1);
3238 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3239 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3242 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3243 match nodes_2_event {
3244 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3245 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3246 assert_eq!(update_add_htlcs.len(), 1);
3247 assert!(update_fulfill_htlcs.is_empty());
3248 assert!(update_fail_htlcs.is_empty());
3249 assert!(update_fail_malformed_htlcs.is_empty());
3251 _ => panic!("Unexpected event"),
3255 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3256 match nodes_2_event {
3257 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3258 assert_eq!(channel_id, chan_2.2);
3259 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3261 _ => panic!("Unexpected event"),
3264 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3265 match nodes_0_event {
3266 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3267 assert!(update_add_htlcs.is_empty());
3268 assert_eq!(update_fail_htlcs.len(), 3);
3269 assert!(update_fulfill_htlcs.is_empty());
3270 assert!(update_fail_malformed_htlcs.is_empty());
3271 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3273 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3274 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3275 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3277 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3279 let events = nodes[0].node.get_and_clear_pending_events();
3280 assert_eq!(events.len(), 6);
3282 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3283 assert!(failed_htlcs.insert(payment_hash.0));
3284 // If we delivered B's RAA we got an unknown preimage error, not something
3285 // that we should update our routing table for.
3286 if !deliver_bs_raa {
3287 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3290 _ => panic!("Unexpected event"),
3293 Event::PaymentFailed { ref payment_hash, .. } => {
3294 assert_eq!(*payment_hash, first_payment_hash);
3296 _ => panic!("Unexpected event"),
3299 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3300 assert!(failed_htlcs.insert(payment_hash.0));
3302 _ => panic!("Unexpected event"),
3305 Event::PaymentFailed { ref payment_hash, .. } => {
3306 assert_eq!(*payment_hash, second_payment_hash);
3308 _ => panic!("Unexpected event"),
3311 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3312 assert!(failed_htlcs.insert(payment_hash.0));
3314 _ => panic!("Unexpected event"),
3317 Event::PaymentFailed { ref payment_hash, .. } => {
3318 assert_eq!(*payment_hash, third_payment_hash);
3320 _ => panic!("Unexpected event"),
3323 _ => panic!("Unexpected event"),
3326 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3328 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3329 _ => panic!("Unexpected event"),
3332 assert!(failed_htlcs.contains(&first_payment_hash.0));
3333 assert!(failed_htlcs.contains(&second_payment_hash.0));
3334 assert!(failed_htlcs.contains(&third_payment_hash.0));
3338 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3339 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3340 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3341 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3342 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3346 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3347 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3348 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3349 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3350 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3354 fn fail_backward_pending_htlc_upon_channel_failure() {
3355 let chanmon_cfgs = create_chanmon_cfgs(2);
3356 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3357 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3358 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3359 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3361 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3363 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3364 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3365 PaymentId(payment_hash.0)).unwrap();
3366 check_added_monitors!(nodes[0], 1);
3368 let payment_event = {
3369 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3370 assert_eq!(events.len(), 1);
3371 SendEvent::from_event(events.remove(0))
3373 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3374 assert_eq!(payment_event.msgs.len(), 1);
3377 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3378 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3380 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3381 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3382 check_added_monitors!(nodes[0], 0);
3384 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3387 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3389 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3391 let secp_ctx = Secp256k1::new();
3392 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3393 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3394 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3395 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3396 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3397 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3399 // Send a 0-msat update_add_htlc to fail the channel.
3400 let update_add_htlc = msgs::UpdateAddHTLC {
3406 onion_routing_packet,
3408 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3410 let events = nodes[0].node.get_and_clear_pending_events();
3411 assert_eq!(events.len(), 3);
3412 // Check that Alice fails backward the pending HTLC from the second payment.
3414 Event::PaymentPathFailed { payment_hash, .. } => {
3415 assert_eq!(payment_hash, failed_payment_hash);
3417 _ => panic!("Unexpected event"),
3420 Event::PaymentFailed { payment_hash, .. } => {
3421 assert_eq!(payment_hash, failed_payment_hash);
3423 _ => panic!("Unexpected event"),
3426 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3427 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3429 _ => panic!("Unexpected event {:?}", events[1]),
3431 check_closed_broadcast!(nodes[0], true);
3432 check_added_monitors!(nodes[0], 1);
3436 fn test_htlc_ignore_latest_remote_commitment() {
3437 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3438 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3439 let chanmon_cfgs = create_chanmon_cfgs(2);
3440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3442 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3443 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3444 // We rely on the ability to connect a block redundantly, which isn't allowed via
3445 // `chain::Listen`, so we never run the test if we randomly get assigned that
3449 create_announced_chan_between_nodes(&nodes, 0, 1);
3451 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3452 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3453 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3454 check_closed_broadcast!(nodes[0], true);
3455 check_added_monitors!(nodes[0], 1);
3456 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3458 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3459 assert_eq!(node_txn.len(), 3);
3460 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3462 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3463 connect_block(&nodes[1], &block);
3464 check_closed_broadcast!(nodes[1], true);
3465 check_added_monitors!(nodes[1], 1);
3466 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3468 // Duplicate the connect_block call since this may happen due to other listeners
3469 // registering new transactions
3470 connect_block(&nodes[1], &block);
3474 fn test_force_close_fail_back() {
3475 // Check which HTLCs are failed-backwards on channel force-closure
3476 let chanmon_cfgs = create_chanmon_cfgs(3);
3477 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3478 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3479 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3480 create_announced_chan_between_nodes(&nodes, 0, 1);
3481 create_announced_chan_between_nodes(&nodes, 1, 2);
3483 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3485 let mut payment_event = {
3486 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3487 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3488 check_added_monitors!(nodes[0], 1);
3490 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3491 assert_eq!(events.len(), 1);
3492 SendEvent::from_event(events.remove(0))
3495 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3496 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3498 expect_pending_htlcs_forwardable!(nodes[1]);
3500 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3501 assert_eq!(events_2.len(), 1);
3502 payment_event = SendEvent::from_event(events_2.remove(0));
3503 assert_eq!(payment_event.msgs.len(), 1);
3505 check_added_monitors!(nodes[1], 1);
3506 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3507 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3508 check_added_monitors!(nodes[2], 1);
3509 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3511 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3512 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3513 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3515 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3516 check_closed_broadcast!(nodes[2], true);
3517 check_added_monitors!(nodes[2], 1);
3518 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3520 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3521 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3522 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3523 // back to nodes[1] upon timeout otherwise.
3524 assert_eq!(node_txn.len(), 1);
3528 mine_transaction(&nodes[1], &tx);
3530 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3531 check_closed_broadcast!(nodes[1], true);
3532 check_added_monitors!(nodes[1], 1);
3533 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3535 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3537 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3538 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3540 mine_transaction(&nodes[2], &tx);
3541 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3542 assert_eq!(node_txn.len(), 1);
3543 assert_eq!(node_txn[0].input.len(), 1);
3544 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3545 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3546 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3548 check_spends!(node_txn[0], tx);
3552 fn test_dup_events_on_peer_disconnect() {
3553 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3554 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3555 // as we used to generate the event immediately upon receipt of the payment preimage in the
3556 // update_fulfill_htlc message.
3558 let chanmon_cfgs = create_chanmon_cfgs(2);
3559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3561 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3562 create_announced_chan_between_nodes(&nodes, 0, 1);
3564 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3566 nodes[1].node.claim_funds(payment_preimage);
3567 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3568 check_added_monitors!(nodes[1], 1);
3569 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3570 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3571 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3573 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3574 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3576 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3577 expect_payment_path_successful!(nodes[0]);
3581 fn test_peer_disconnected_before_funding_broadcasted() {
3582 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3583 // before the funding transaction has been broadcasted.
3584 let chanmon_cfgs = create_chanmon_cfgs(2);
3585 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3586 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3587 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3589 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3590 // broadcasted, even though it's created by `nodes[0]`.
3591 let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3592 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3593 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3594 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3595 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3597 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3598 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3600 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3602 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3603 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3605 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3606 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3609 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3612 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3613 // disconnected before the funding transaction was broadcasted.
3614 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3615 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3617 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3618 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3622 fn test_simple_peer_disconnect() {
3623 // Test that we can reconnect when there are no lost messages
3624 let chanmon_cfgs = create_chanmon_cfgs(3);
3625 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3626 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3627 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3628 create_announced_chan_between_nodes(&nodes, 0, 1);
3629 create_announced_chan_between_nodes(&nodes, 1, 2);
3631 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3632 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3633 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3635 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3636 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3637 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3638 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3640 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3641 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3642 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3644 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3645 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3646 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3647 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3649 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3650 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3652 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3653 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3655 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3657 let events = nodes[0].node.get_and_clear_pending_events();
3658 assert_eq!(events.len(), 4);
3660 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3661 assert_eq!(payment_preimage, payment_preimage_3);
3662 assert_eq!(payment_hash, payment_hash_3);
3664 _ => panic!("Unexpected event"),
3667 Event::PaymentPathSuccessful { .. } => {},
3668 _ => panic!("Unexpected event"),
3671 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3672 assert_eq!(payment_hash, payment_hash_5);
3673 assert!(payment_failed_permanently);
3675 _ => panic!("Unexpected event"),
3678 Event::PaymentFailed { payment_hash, .. } => {
3679 assert_eq!(payment_hash, payment_hash_5);
3681 _ => panic!("Unexpected event"),
3685 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3686 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3689 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3690 // Test that we can reconnect when in-flight HTLC updates get dropped
3691 let chanmon_cfgs = create_chanmon_cfgs(2);
3692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3694 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3696 let mut as_channel_ready = None;
3697 let channel_id = if messages_delivered == 0 {
3698 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3699 as_channel_ready = Some(channel_ready);
3700 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3701 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3702 // it before the channel_reestablish message.
3705 create_announced_chan_between_nodes(&nodes, 0, 1).2
3708 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3710 let payment_event = {
3711 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3712 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3713 check_added_monitors!(nodes[0], 1);
3715 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3716 assert_eq!(events.len(), 1);
3717 SendEvent::from_event(events.remove(0))
3719 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3721 if messages_delivered < 2 {
3722 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3724 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3725 if messages_delivered >= 3 {
3726 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3727 check_added_monitors!(nodes[1], 1);
3728 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3730 if messages_delivered >= 4 {
3731 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3732 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3733 check_added_monitors!(nodes[0], 1);
3735 if messages_delivered >= 5 {
3736 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3737 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3738 // No commitment_signed so get_event_msg's assert(len == 1) passes
3739 check_added_monitors!(nodes[0], 1);
3741 if messages_delivered >= 6 {
3742 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3743 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3744 check_added_monitors!(nodes[1], 1);
3751 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3752 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3753 if messages_delivered < 3 {
3754 if simulate_broken_lnd {
3755 // lnd has a long-standing bug where they send a channel_ready prior to a
3756 // channel_reestablish if you reconnect prior to channel_ready time.
3758 // Here we simulate that behavior, delivering a channel_ready immediately on
3759 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3760 // in `reconnect_nodes` but we currently don't fail based on that.
3762 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3763 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3765 // Even if the channel_ready messages get exchanged, as long as nothing further was
3766 // received on either side, both sides will need to resend them.
3767 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3768 } else if messages_delivered == 3 {
3769 // nodes[0] still wants its RAA + commitment_signed
3770 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3771 } else if messages_delivered == 4 {
3772 // nodes[0] still wants its commitment_signed
3773 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3774 } else if messages_delivered == 5 {
3775 // nodes[1] still wants its final RAA
3776 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3777 } else if messages_delivered == 6 {
3778 // Everything was delivered...
3779 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3782 let events_1 = nodes[1].node.get_and_clear_pending_events();
3783 if messages_delivered == 0 {
3784 assert_eq!(events_1.len(), 2);
3786 Event::ChannelReady { .. } => { },
3787 _ => panic!("Unexpected event"),
3790 Event::PendingHTLCsForwardable { .. } => { },
3791 _ => panic!("Unexpected event"),
3794 assert_eq!(events_1.len(), 1);
3796 Event::PendingHTLCsForwardable { .. } => { },
3797 _ => panic!("Unexpected event"),
3801 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3802 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3803 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3805 nodes[1].node.process_pending_htlc_forwards();
3807 let events_2 = nodes[1].node.get_and_clear_pending_events();
3808 assert_eq!(events_2.len(), 1);
3810 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3811 assert_eq!(payment_hash_1, *payment_hash);
3812 assert_eq!(amount_msat, 1_000_000);
3813 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3814 assert_eq!(via_channel_id, Some(channel_id));
3816 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3817 assert!(payment_preimage.is_none());
3818 assert_eq!(payment_secret_1, *payment_secret);
3820 _ => panic!("expected PaymentPurpose::InvoicePayment")
3823 _ => panic!("Unexpected event"),
3826 nodes[1].node.claim_funds(payment_preimage_1);
3827 check_added_monitors!(nodes[1], 1);
3828 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3830 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3831 assert_eq!(events_3.len(), 1);
3832 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3833 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3834 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3835 assert!(updates.update_add_htlcs.is_empty());
3836 assert!(updates.update_fail_htlcs.is_empty());
3837 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3838 assert!(updates.update_fail_malformed_htlcs.is_empty());
3839 assert!(updates.update_fee.is_none());
3840 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3842 _ => panic!("Unexpected event"),
3845 if messages_delivered >= 1 {
3846 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3848 let events_4 = nodes[0].node.get_and_clear_pending_events();
3849 assert_eq!(events_4.len(), 1);
3851 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3852 assert_eq!(payment_preimage_1, *payment_preimage);
3853 assert_eq!(payment_hash_1, *payment_hash);
3855 _ => panic!("Unexpected event"),
3858 if messages_delivered >= 2 {
3859 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3860 check_added_monitors!(nodes[0], 1);
3861 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3863 if messages_delivered >= 3 {
3864 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3865 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3866 check_added_monitors!(nodes[1], 1);
3868 if messages_delivered >= 4 {
3869 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3870 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3871 // No commitment_signed so get_event_msg's assert(len == 1) passes
3872 check_added_monitors!(nodes[1], 1);
3874 if messages_delivered >= 5 {
3875 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3876 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3877 check_added_monitors!(nodes[0], 1);
3884 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3885 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3886 if messages_delivered < 2 {
3887 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3888 if messages_delivered < 1 {
3889 expect_payment_sent!(nodes[0], payment_preimage_1);
3891 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3893 } else if messages_delivered == 2 {
3894 // nodes[0] still wants its RAA + commitment_signed
3895 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3896 } else if messages_delivered == 3 {
3897 // nodes[0] still wants its commitment_signed
3898 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3899 } else if messages_delivered == 4 {
3900 // nodes[1] still wants its final RAA
3901 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3902 } else if messages_delivered == 5 {
3903 // Everything was delivered...
3904 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3907 if messages_delivered == 1 || messages_delivered == 2 {
3908 expect_payment_path_successful!(nodes[0]);
3910 if messages_delivered <= 5 {
3911 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3912 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3914 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3916 if messages_delivered > 2 {
3917 expect_payment_path_successful!(nodes[0]);
3920 // Channel should still work fine...
3921 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3922 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3923 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3927 fn test_drop_messages_peer_disconnect_a() {
3928 do_test_drop_messages_peer_disconnect(0, true);
3929 do_test_drop_messages_peer_disconnect(0, false);
3930 do_test_drop_messages_peer_disconnect(1, false);
3931 do_test_drop_messages_peer_disconnect(2, false);
3935 fn test_drop_messages_peer_disconnect_b() {
3936 do_test_drop_messages_peer_disconnect(3, false);
3937 do_test_drop_messages_peer_disconnect(4, false);
3938 do_test_drop_messages_peer_disconnect(5, false);
3939 do_test_drop_messages_peer_disconnect(6, false);
3943 fn test_channel_ready_without_best_block_updated() {
3944 // Previously, if we were offline when a funding transaction was locked in, and then we came
3945 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3946 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3947 // channel_ready immediately instead.
3948 let chanmon_cfgs = create_chanmon_cfgs(2);
3949 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3950 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3951 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3952 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3954 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3956 let conf_height = nodes[0].best_block_info().1 + 1;
3957 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3958 let block_txn = [funding_tx];
3959 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3960 let conf_block_header = nodes[0].get_block_header(conf_height);
3961 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3963 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3964 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3965 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3969 fn test_drop_messages_peer_disconnect_dual_htlc() {
3970 // Test that we can handle reconnecting when both sides of a channel have pending
3971 // commitment_updates when we disconnect.
3972 let chanmon_cfgs = create_chanmon_cfgs(2);
3973 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3974 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3975 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3976 create_announced_chan_between_nodes(&nodes, 0, 1);
3978 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3980 // Now try to send a second payment which will fail to send
3981 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3982 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3983 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3984 check_added_monitors!(nodes[0], 1);
3986 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3987 assert_eq!(events_1.len(), 1);
3989 MessageSendEvent::UpdateHTLCs { .. } => {},
3990 _ => panic!("Unexpected event"),
3993 nodes[1].node.claim_funds(payment_preimage_1);
3994 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3995 check_added_monitors!(nodes[1], 1);
3997 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3998 assert_eq!(events_2.len(), 1);
4000 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
4001 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4002 assert!(update_add_htlcs.is_empty());
4003 assert_eq!(update_fulfill_htlcs.len(), 1);
4004 assert!(update_fail_htlcs.is_empty());
4005 assert!(update_fail_malformed_htlcs.is_empty());
4006 assert!(update_fee.is_none());
4008 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4009 let events_3 = nodes[0].node.get_and_clear_pending_events();
4010 assert_eq!(events_3.len(), 1);
4012 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4013 assert_eq!(*payment_preimage, payment_preimage_1);
4014 assert_eq!(*payment_hash, payment_hash_1);
4016 _ => panic!("Unexpected event"),
4019 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4020 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4021 // No commitment_signed so get_event_msg's assert(len == 1) passes
4022 check_added_monitors!(nodes[0], 1);
4024 _ => panic!("Unexpected event"),
4027 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4028 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4030 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4031 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4033 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4034 assert_eq!(reestablish_1.len(), 1);
4035 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4036 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4038 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4039 assert_eq!(reestablish_2.len(), 1);
4041 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4042 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4043 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4044 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4046 assert!(as_resp.0.is_none());
4047 assert!(bs_resp.0.is_none());
4049 assert!(bs_resp.1.is_none());
4050 assert!(bs_resp.2.is_none());
4052 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4054 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4055 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4056 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4057 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4058 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4059 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4060 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4061 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4062 // No commitment_signed so get_event_msg's assert(len == 1) passes
4063 check_added_monitors!(nodes[1], 1);
4065 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4066 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4067 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4068 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4069 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4070 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4071 assert!(bs_second_commitment_signed.update_fee.is_none());
4072 check_added_monitors!(nodes[1], 1);
4074 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4075 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4076 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4077 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4078 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4079 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4080 assert!(as_commitment_signed.update_fee.is_none());
4081 check_added_monitors!(nodes[0], 1);
4083 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4084 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4085 // No commitment_signed so get_event_msg's assert(len == 1) passes
4086 check_added_monitors!(nodes[0], 1);
4088 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4089 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4090 // No commitment_signed so get_event_msg's assert(len == 1) passes
4091 check_added_monitors!(nodes[1], 1);
4093 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4094 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4095 check_added_monitors!(nodes[1], 1);
4097 expect_pending_htlcs_forwardable!(nodes[1]);
4099 let events_5 = nodes[1].node.get_and_clear_pending_events();
4100 assert_eq!(events_5.len(), 1);
4102 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4103 assert_eq!(payment_hash_2, *payment_hash);
4105 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4106 assert!(payment_preimage.is_none());
4107 assert_eq!(payment_secret_2, *payment_secret);
4109 _ => panic!("expected PaymentPurpose::InvoicePayment")
4112 _ => panic!("Unexpected event"),
4115 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4116 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4117 check_added_monitors!(nodes[0], 1);
4119 expect_payment_path_successful!(nodes[0]);
4120 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4123 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4124 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4125 // to avoid our counterparty failing the channel.
4126 let chanmon_cfgs = create_chanmon_cfgs(2);
4127 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4129 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4131 create_announced_chan_between_nodes(&nodes, 0, 1);
4133 let our_payment_hash = if send_partial_mpp {
4134 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4135 // Use the utility function send_payment_along_path to send the payment with MPP data which
4136 // indicates there are more HTLCs coming.
4137 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.
4138 let payment_id = PaymentId([42; 32]);
4139 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4140 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4141 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4142 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4143 &None, session_privs[0]).unwrap();
4144 check_added_monitors!(nodes[0], 1);
4145 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4146 assert_eq!(events.len(), 1);
4147 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4148 // hop should *not* yet generate any PaymentClaimable event(s).
4149 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4152 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4155 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4156 connect_block(&nodes[0], &block);
4157 connect_block(&nodes[1], &block);
4158 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4159 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4160 block.header.prev_blockhash = block.block_hash();
4161 connect_block(&nodes[0], &block);
4162 connect_block(&nodes[1], &block);
4165 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4167 check_added_monitors!(nodes[1], 1);
4168 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4169 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4170 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4171 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4172 assert!(htlc_timeout_updates.update_fee.is_none());
4174 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4175 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4176 // 100_000 msat as u64, followed by the height at which we failed back above
4177 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4178 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4179 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4183 fn test_htlc_timeout() {
4184 do_test_htlc_timeout(true);
4185 do_test_htlc_timeout(false);
4188 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4189 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4190 let chanmon_cfgs = create_chanmon_cfgs(3);
4191 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4192 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4193 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4194 create_announced_chan_between_nodes(&nodes, 0, 1);
4195 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4197 // Make sure all nodes are at the same starting height
4198 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4199 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4200 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4202 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4203 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4204 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4205 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4206 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4207 check_added_monitors!(nodes[1], 1);
4209 // Now attempt to route a second payment, which should be placed in the holding cell
4210 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4211 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4212 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4213 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4215 check_added_monitors!(nodes[0], 1);
4216 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4217 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4218 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4219 expect_pending_htlcs_forwardable!(nodes[1]);
4221 check_added_monitors!(nodes[1], 0);
4223 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4224 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4225 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4226 connect_blocks(&nodes[1], 1);
4229 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 }]);
4230 check_added_monitors!(nodes[1], 1);
4231 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4232 assert_eq!(fail_commit.len(), 1);
4233 match fail_commit[0] {
4234 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4235 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4236 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4238 _ => unreachable!(),
4240 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4242 expect_payment_failed!(nodes[1], second_payment_hash, false);
4247 fn test_holding_cell_htlc_add_timeouts() {
4248 do_test_holding_cell_htlc_add_timeouts(false);
4249 do_test_holding_cell_htlc_add_timeouts(true);
4252 macro_rules! check_spendable_outputs {
4253 ($node: expr, $keysinterface: expr) => {
4255 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4256 let mut txn = Vec::new();
4257 let mut all_outputs = Vec::new();
4258 let secp_ctx = Secp256k1::new();
4259 for event in events.drain(..) {
4261 Event::SpendableOutputs { mut outputs } => {
4262 for outp in outputs.drain(..) {
4263 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());
4264 all_outputs.push(outp);
4267 _ => panic!("Unexpected event"),
4270 if all_outputs.len() > 1 {
4271 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) {
4281 fn test_claim_sizeable_push_msat() {
4282 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4283 let chanmon_cfgs = create_chanmon_cfgs(2);
4284 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4285 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4286 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4288 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4289 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4290 check_closed_broadcast!(nodes[1], true);
4291 check_added_monitors!(nodes[1], 1);
4292 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4293 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4294 assert_eq!(node_txn.len(), 1);
4295 check_spends!(node_txn[0], chan.3);
4296 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
4298 mine_transaction(&nodes[1], &node_txn[0]);
4299 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4301 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4302 assert_eq!(spend_txn.len(), 1);
4303 assert_eq!(spend_txn[0].input.len(), 1);
4304 check_spends!(spend_txn[0], node_txn[0]);
4305 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4309 fn test_claim_on_remote_sizeable_push_msat() {
4310 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4311 // to_remote output is encumbered by a P2WPKH
4312 let chanmon_cfgs = create_chanmon_cfgs(2);
4313 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4314 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4315 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4317 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4318 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4319 check_closed_broadcast!(nodes[0], true);
4320 check_added_monitors!(nodes[0], 1);
4321 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4323 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4324 assert_eq!(node_txn.len(), 1);
4325 check_spends!(node_txn[0], chan.3);
4326 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
4328 mine_transaction(&nodes[1], &node_txn[0]);
4329 check_closed_broadcast!(nodes[1], true);
4330 check_added_monitors!(nodes[1], 1);
4331 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4332 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4334 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4335 assert_eq!(spend_txn.len(), 1);
4336 check_spends!(spend_txn[0], node_txn[0]);
4340 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4341 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4342 // to_remote output is encumbered by a P2WPKH
4344 let chanmon_cfgs = create_chanmon_cfgs(2);
4345 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4346 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4347 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4349 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4350 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4351 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4352 assert_eq!(revoked_local_txn[0].input.len(), 1);
4353 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4355 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4356 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4357 check_closed_broadcast!(nodes[1], true);
4358 check_added_monitors!(nodes[1], 1);
4359 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4361 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4362 mine_transaction(&nodes[1], &node_txn[0]);
4363 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4365 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4366 assert_eq!(spend_txn.len(), 3);
4367 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4368 check_spends!(spend_txn[1], node_txn[0]);
4369 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4373 fn test_static_spendable_outputs_preimage_tx() {
4374 let chanmon_cfgs = create_chanmon_cfgs(2);
4375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4377 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4379 // Create some initial channels
4380 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4382 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4384 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4385 assert_eq!(commitment_tx[0].input.len(), 1);
4386 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4388 // Settle A's commitment tx on B's chain
4389 nodes[1].node.claim_funds(payment_preimage);
4390 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4391 check_added_monitors!(nodes[1], 1);
4392 mine_transaction(&nodes[1], &commitment_tx[0]);
4393 check_added_monitors!(nodes[1], 1);
4394 let events = nodes[1].node.get_and_clear_pending_msg_events();
4396 MessageSendEvent::UpdateHTLCs { .. } => {},
4397 _ => panic!("Unexpected event"),
4400 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4401 _ => panic!("Unexepected event"),
4404 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4405 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4406 assert_eq!(node_txn.len(), 1);
4407 check_spends!(node_txn[0], commitment_tx[0]);
4408 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4410 mine_transaction(&nodes[1], &node_txn[0]);
4411 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4412 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4414 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4415 assert_eq!(spend_txn.len(), 1);
4416 check_spends!(spend_txn[0], node_txn[0]);
4420 fn test_static_spendable_outputs_timeout_tx() {
4421 let chanmon_cfgs = create_chanmon_cfgs(2);
4422 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4423 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4424 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4426 // Create some initial channels
4427 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4429 // Rebalance the network a bit by relaying one payment through all the channels ...
4430 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4432 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4434 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4435 assert_eq!(commitment_tx[0].input.len(), 1);
4436 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4438 // Settle A's commitment tx on B' chain
4439 mine_transaction(&nodes[1], &commitment_tx[0]);
4440 check_added_monitors!(nodes[1], 1);
4441 let events = nodes[1].node.get_and_clear_pending_msg_events();
4443 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4444 _ => panic!("Unexpected event"),
4446 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4448 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4449 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4450 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4451 check_spends!(node_txn[0], commitment_tx[0].clone());
4452 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4454 mine_transaction(&nodes[1], &node_txn[0]);
4455 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4456 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4457 expect_payment_failed!(nodes[1], our_payment_hash, false);
4459 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4460 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4461 check_spends!(spend_txn[0], commitment_tx[0]);
4462 check_spends!(spend_txn[1], node_txn[0]);
4463 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4467 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4468 let chanmon_cfgs = create_chanmon_cfgs(2);
4469 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4470 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4471 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4473 // Create some initial channels
4474 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4476 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4477 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4478 assert_eq!(revoked_local_txn[0].input.len(), 1);
4479 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4481 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4483 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4484 check_closed_broadcast!(nodes[1], true);
4485 check_added_monitors!(nodes[1], 1);
4486 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4488 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4489 assert_eq!(node_txn.len(), 1);
4490 assert_eq!(node_txn[0].input.len(), 2);
4491 check_spends!(node_txn[0], revoked_local_txn[0]);
4493 mine_transaction(&nodes[1], &node_txn[0]);
4494 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4496 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4497 assert_eq!(spend_txn.len(), 1);
4498 check_spends!(spend_txn[0], node_txn[0]);
4502 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4503 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4504 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4505 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4506 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4507 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4509 // Create some initial channels
4510 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4512 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4513 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4514 assert_eq!(revoked_local_txn[0].input.len(), 1);
4515 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4517 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4519 // A will generate HTLC-Timeout from revoked commitment tx
4520 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4521 check_closed_broadcast!(nodes[0], true);
4522 check_added_monitors!(nodes[0], 1);
4523 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4524 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4526 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4527 assert_eq!(revoked_htlc_txn.len(), 1);
4528 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4529 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4530 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4531 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4533 // B will generate justice tx from A's revoked commitment/HTLC tx
4534 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4535 check_closed_broadcast!(nodes[1], true);
4536 check_added_monitors!(nodes[1], 1);
4537 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4539 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4540 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4541 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4542 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4543 // transactions next...
4544 assert_eq!(node_txn[0].input.len(), 3);
4545 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4547 assert_eq!(node_txn[1].input.len(), 2);
4548 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4549 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4550 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4552 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4553 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4556 mine_transaction(&nodes[1], &node_txn[1]);
4557 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4559 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4560 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4561 assert_eq!(spend_txn.len(), 1);
4562 assert_eq!(spend_txn[0].input.len(), 1);
4563 check_spends!(spend_txn[0], node_txn[1]);
4567 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4568 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4569 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4572 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4574 // Create some initial channels
4575 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4577 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4578 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4579 assert_eq!(revoked_local_txn[0].input.len(), 1);
4580 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4582 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4583 assert_eq!(revoked_local_txn[0].output.len(), 2);
4585 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4587 // B will generate HTLC-Success from revoked commitment tx
4588 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4589 check_closed_broadcast!(nodes[1], true);
4590 check_added_monitors!(nodes[1], 1);
4591 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4592 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4594 assert_eq!(revoked_htlc_txn.len(), 1);
4595 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4596 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4597 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4599 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4600 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4601 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4603 // A will generate justice tx from B's revoked commitment/HTLC tx
4604 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4605 check_closed_broadcast!(nodes[0], true);
4606 check_added_monitors!(nodes[0], 1);
4607 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4609 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4610 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4612 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4613 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4614 // transactions next...
4615 assert_eq!(node_txn[0].input.len(), 2);
4616 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4617 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4618 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4620 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4621 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4624 assert_eq!(node_txn[1].input.len(), 1);
4625 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4627 mine_transaction(&nodes[0], &node_txn[1]);
4628 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4630 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4631 // didn't try to generate any new transactions.
4633 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4634 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4635 assert_eq!(spend_txn.len(), 3);
4636 assert_eq!(spend_txn[0].input.len(), 1);
4637 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4638 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4639 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4640 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4644 fn test_onchain_to_onchain_claim() {
4645 // Test that in case of channel closure, we detect the state of output and claim HTLC
4646 // on downstream peer's remote commitment tx.
4647 // First, have C claim an HTLC against its own latest commitment transaction.
4648 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4650 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4653 let chanmon_cfgs = create_chanmon_cfgs(3);
4654 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4655 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4656 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4658 // Create some initial channels
4659 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4660 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4662 // Ensure all nodes are at the same height
4663 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4664 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4665 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4666 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4668 // Rebalance the network a bit by relaying one payment through all the channels ...
4669 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4670 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4672 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4673 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4674 check_spends!(commitment_tx[0], chan_2.3);
4675 nodes[2].node.claim_funds(payment_preimage);
4676 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4677 check_added_monitors!(nodes[2], 1);
4678 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4679 assert!(updates.update_add_htlcs.is_empty());
4680 assert!(updates.update_fail_htlcs.is_empty());
4681 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4682 assert!(updates.update_fail_malformed_htlcs.is_empty());
4684 mine_transaction(&nodes[2], &commitment_tx[0]);
4685 check_closed_broadcast!(nodes[2], true);
4686 check_added_monitors!(nodes[2], 1);
4687 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4689 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4690 assert_eq!(c_txn.len(), 1);
4691 check_spends!(c_txn[0], commitment_tx[0]);
4692 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4693 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4694 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4696 // 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
4697 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4698 check_added_monitors!(nodes[1], 1);
4699 let events = nodes[1].node.get_and_clear_pending_events();
4700 assert_eq!(events.len(), 2);
4702 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4703 _ => panic!("Unexpected event"),
4706 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4707 assert_eq!(fee_earned_msat, Some(1000));
4708 assert_eq!(prev_channel_id, Some(chan_1.2));
4709 assert_eq!(claim_from_onchain_tx, true);
4710 assert_eq!(next_channel_id, Some(chan_2.2));
4711 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4713 _ => panic!("Unexpected event"),
4715 check_added_monitors!(nodes[1], 1);
4716 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4717 assert_eq!(msg_events.len(), 3);
4718 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4719 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4721 match nodes_2_event {
4722 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4723 _ => panic!("Unexpected event"),
4726 match nodes_0_event {
4727 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, .. } } => {
4728 assert!(update_add_htlcs.is_empty());
4729 assert!(update_fail_htlcs.is_empty());
4730 assert_eq!(update_fulfill_htlcs.len(), 1);
4731 assert!(update_fail_malformed_htlcs.is_empty());
4732 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4734 _ => panic!("Unexpected event"),
4737 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4738 match msg_events[0] {
4739 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4740 _ => panic!("Unexpected event"),
4743 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4744 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4745 mine_transaction(&nodes[1], &commitment_tx[0]);
4746 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4747 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4748 // ChannelMonitor: HTLC-Success tx
4749 assert_eq!(b_txn.len(), 1);
4750 check_spends!(b_txn[0], commitment_tx[0]);
4751 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4752 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4753 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4755 check_closed_broadcast!(nodes[1], true);
4756 check_added_monitors!(nodes[1], 1);
4760 fn test_duplicate_payment_hash_one_failure_one_success() {
4761 // Topology : A --> B --> C --> D
4762 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4763 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4764 // we forward one of the payments onwards to D.
4765 let chanmon_cfgs = create_chanmon_cfgs(4);
4766 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4767 // When this test was written, the default base fee floated based on the HTLC count.
4768 // It is now fixed, so we simply set the fee to the expected value here.
4769 let mut config = test_default_channel_config();
4770 config.channel_config.forwarding_fee_base_msat = 196;
4771 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4772 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4773 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4775 create_announced_chan_between_nodes(&nodes, 0, 1);
4776 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4777 create_announced_chan_between_nodes(&nodes, 2, 3);
4779 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4780 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4781 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4782 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4783 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4785 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4787 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4788 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4789 // script push size limit so that the below script length checks match
4790 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4791 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4792 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4793 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4794 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4796 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4797 assert_eq!(commitment_txn[0].input.len(), 1);
4798 check_spends!(commitment_txn[0], chan_2.3);
4800 mine_transaction(&nodes[1], &commitment_txn[0]);
4801 check_closed_broadcast!(nodes[1], true);
4802 check_added_monitors!(nodes[1], 1);
4803 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4804 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4806 let htlc_timeout_tx;
4807 { // Extract one of the two HTLC-Timeout transaction
4808 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4809 // ChannelMonitor: timeout tx * 2-or-3
4810 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4812 check_spends!(node_txn[0], commitment_txn[0]);
4813 assert_eq!(node_txn[0].input.len(), 1);
4814 assert_eq!(node_txn[0].output.len(), 1);
4816 if node_txn.len() > 2 {
4817 check_spends!(node_txn[1], commitment_txn[0]);
4818 assert_eq!(node_txn[1].input.len(), 1);
4819 assert_eq!(node_txn[1].output.len(), 1);
4820 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4822 check_spends!(node_txn[2], commitment_txn[0]);
4823 assert_eq!(node_txn[2].input.len(), 1);
4824 assert_eq!(node_txn[2].output.len(), 1);
4825 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
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_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4833 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4834 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4835 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4836 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4837 if node_txn.len() > 2 {
4838 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4839 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4841 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4845 nodes[2].node.claim_funds(our_payment_preimage);
4846 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4848 mine_transaction(&nodes[2], &commitment_txn[0]);
4849 check_added_monitors!(nodes[2], 2);
4850 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4851 let events = nodes[2].node.get_and_clear_pending_msg_events();
4853 MessageSendEvent::UpdateHTLCs { .. } => {},
4854 _ => panic!("Unexpected event"),
4857 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4858 _ => panic!("Unexepected event"),
4860 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4861 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4862 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4863 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4864 assert_eq!(htlc_success_txn[0].input.len(), 1);
4865 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4866 assert_eq!(htlc_success_txn[1].input.len(), 1);
4867 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4868 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4869 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4871 mine_transaction(&nodes[1], &htlc_timeout_tx);
4872 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4873 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 }]);
4874 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4875 assert!(htlc_updates.update_add_htlcs.is_empty());
4876 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4877 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4878 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4879 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4880 check_added_monitors!(nodes[1], 1);
4882 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4883 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4885 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4887 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4889 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4890 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4891 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4892 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4893 assert!(updates.update_add_htlcs.is_empty());
4894 assert!(updates.update_fail_htlcs.is_empty());
4895 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4896 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4897 assert!(updates.update_fail_malformed_htlcs.is_empty());
4898 check_added_monitors!(nodes[1], 1);
4900 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4901 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4902 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4906 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4907 let chanmon_cfgs = create_chanmon_cfgs(2);
4908 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4909 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4910 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4912 // Create some initial channels
4913 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4915 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4916 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4917 assert_eq!(local_txn.len(), 1);
4918 assert_eq!(local_txn[0].input.len(), 1);
4919 check_spends!(local_txn[0], chan_1.3);
4921 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4922 nodes[1].node.claim_funds(payment_preimage);
4923 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4924 check_added_monitors!(nodes[1], 1);
4926 mine_transaction(&nodes[1], &local_txn[0]);
4927 check_added_monitors!(nodes[1], 1);
4928 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4929 let events = nodes[1].node.get_and_clear_pending_msg_events();
4931 MessageSendEvent::UpdateHTLCs { .. } => {},
4932 _ => panic!("Unexpected event"),
4935 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4936 _ => panic!("Unexepected event"),
4939 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4940 assert_eq!(node_txn.len(), 1);
4941 assert_eq!(node_txn[0].input.len(), 1);
4942 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4943 check_spends!(node_txn[0], local_txn[0]);
4947 mine_transaction(&nodes[1], &node_tx);
4948 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4950 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4951 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4952 assert_eq!(spend_txn.len(), 1);
4953 assert_eq!(spend_txn[0].input.len(), 1);
4954 check_spends!(spend_txn[0], node_tx);
4955 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4958 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4959 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4960 // unrevoked commitment transaction.
4961 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4962 // a remote RAA before they could be failed backwards (and combinations thereof).
4963 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4964 // use the same payment hashes.
4965 // Thus, we use a six-node network:
4970 // And test where C fails back to A/B when D announces its latest commitment transaction
4971 let chanmon_cfgs = create_chanmon_cfgs(6);
4972 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4973 // When this test was written, the default base fee floated based on the HTLC count.
4974 // It is now fixed, so we simply set the fee to the expected value here.
4975 let mut config = test_default_channel_config();
4976 config.channel_config.forwarding_fee_base_msat = 196;
4977 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4978 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4979 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4981 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4982 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4983 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4984 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4985 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4987 // Rebalance and check output sanity...
4988 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4989 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4990 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4992 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4993 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
4995 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
4997 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
4998 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5000 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
5002 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
5004 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5006 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5007 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5009 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());
5011 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());
5014 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5016 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5017 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
5020 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
5022 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5023 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());
5025 // Double-check that six of the new HTLC were added
5026 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5027 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5028 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5029 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5031 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5032 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5033 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5034 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5035 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5036 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5037 check_added_monitors!(nodes[4], 0);
5039 let failed_destinations = vec![
5040 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5041 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5042 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5043 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5045 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5046 check_added_monitors!(nodes[4], 1);
5048 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5049 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5050 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5051 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5052 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5053 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5055 // Fail 3rd below-dust and 7th above-dust HTLCs
5056 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5057 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5058 check_added_monitors!(nodes[5], 0);
5060 let failed_destinations_2 = vec![
5061 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5062 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5064 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5065 check_added_monitors!(nodes[5], 1);
5067 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5068 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5069 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5070 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5072 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5074 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5075 let failed_destinations_3 = vec![
5076 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5077 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5078 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5079 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5080 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5081 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5083 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5084 check_added_monitors!(nodes[3], 1);
5085 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5086 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5087 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5088 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5089 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5090 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5091 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5092 if deliver_last_raa {
5093 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5095 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5098 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5099 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5100 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5101 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5103 // We now broadcast the latest commitment transaction, which *should* result in failures for
5104 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5105 // the non-broadcast above-dust HTLCs.
5107 // Alternatively, we may broadcast the previous commitment transaction, which should only
5108 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5109 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5111 if announce_latest {
5112 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5114 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5116 let events = nodes[2].node.get_and_clear_pending_events();
5117 let close_event = if deliver_last_raa {
5118 assert_eq!(events.len(), 2 + 6);
5119 events.last().clone().unwrap()
5121 assert_eq!(events.len(), 1);
5122 events.last().clone().unwrap()
5125 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5126 _ => panic!("Unexpected event"),
5129 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5130 check_closed_broadcast!(nodes[2], true);
5131 if deliver_last_raa {
5132 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5134 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();
5135 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5137 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5138 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5140 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5143 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5145 check_added_monitors!(nodes[2], 3);
5147 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5148 assert_eq!(cs_msgs.len(), 2);
5149 let mut a_done = false;
5150 for msg in cs_msgs {
5152 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5153 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5154 // should be failed-backwards here.
5155 let target = if *node_id == nodes[0].node.get_our_node_id() {
5156 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5157 for htlc in &updates.update_fail_htlcs {
5158 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 });
5160 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5165 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5166 for htlc in &updates.update_fail_htlcs {
5167 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5169 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5170 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5173 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5174 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5175 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5176 if announce_latest {
5177 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5178 if *node_id == nodes[0].node.get_our_node_id() {
5179 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5182 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5184 _ => panic!("Unexpected event"),
5188 let as_events = nodes[0].node.get_and_clear_pending_events();
5189 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5190 let mut as_failds = HashSet::new();
5191 let mut as_updates = 0;
5192 for event in as_events.iter() {
5193 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5194 assert!(as_failds.insert(*payment_hash));
5195 if *payment_hash != payment_hash_2 {
5196 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5198 assert!(!payment_failed_permanently);
5200 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5203 } else if let &Event::PaymentFailed { .. } = event {
5204 } else { panic!("Unexpected event"); }
5206 assert!(as_failds.contains(&payment_hash_1));
5207 assert!(as_failds.contains(&payment_hash_2));
5208 if announce_latest {
5209 assert!(as_failds.contains(&payment_hash_3));
5210 assert!(as_failds.contains(&payment_hash_5));
5212 assert!(as_failds.contains(&payment_hash_6));
5214 let bs_events = nodes[1].node.get_and_clear_pending_events();
5215 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5216 let mut bs_failds = HashSet::new();
5217 let mut bs_updates = 0;
5218 for event in bs_events.iter() {
5219 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5220 assert!(bs_failds.insert(*payment_hash));
5221 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5222 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5224 assert!(!payment_failed_permanently);
5226 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5229 } else if let &Event::PaymentFailed { .. } = event {
5230 } else { panic!("Unexpected event"); }
5232 assert!(bs_failds.contains(&payment_hash_1));
5233 assert!(bs_failds.contains(&payment_hash_2));
5234 if announce_latest {
5235 assert!(bs_failds.contains(&payment_hash_4));
5237 assert!(bs_failds.contains(&payment_hash_5));
5239 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5240 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5241 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5242 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5243 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5244 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5248 fn test_fail_backwards_latest_remote_announce_a() {
5249 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5253 fn test_fail_backwards_latest_remote_announce_b() {
5254 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5258 fn test_fail_backwards_previous_remote_announce() {
5259 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5260 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5261 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5265 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5266 let chanmon_cfgs = create_chanmon_cfgs(2);
5267 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5268 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5269 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5271 // Create some initial channels
5272 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5274 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5275 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5276 assert_eq!(local_txn[0].input.len(), 1);
5277 check_spends!(local_txn[0], chan_1.3);
5279 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5280 mine_transaction(&nodes[0], &local_txn[0]);
5281 check_closed_broadcast!(nodes[0], true);
5282 check_added_monitors!(nodes[0], 1);
5283 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5284 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5286 let htlc_timeout = {
5287 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5288 assert_eq!(node_txn.len(), 1);
5289 assert_eq!(node_txn[0].input.len(), 1);
5290 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5291 check_spends!(node_txn[0], local_txn[0]);
5295 mine_transaction(&nodes[0], &htlc_timeout);
5296 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5297 expect_payment_failed!(nodes[0], our_payment_hash, false);
5299 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5300 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5301 assert_eq!(spend_txn.len(), 3);
5302 check_spends!(spend_txn[0], local_txn[0]);
5303 assert_eq!(spend_txn[1].input.len(), 1);
5304 check_spends!(spend_txn[1], htlc_timeout);
5305 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5306 assert_eq!(spend_txn[2].input.len(), 2);
5307 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5308 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5309 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5313 fn test_key_derivation_params() {
5314 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5315 // manager rotation to test that `channel_keys_id` returned in
5316 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5317 // then derive a `delayed_payment_key`.
5319 let chanmon_cfgs = create_chanmon_cfgs(3);
5321 // We manually create the node configuration to backup the seed.
5322 let seed = [42; 32];
5323 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5324 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);
5325 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5326 let scorer = Mutex::new(test_utils::TestScorer::new());
5327 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5328 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)) };
5329 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5330 node_cfgs.remove(0);
5331 node_cfgs.insert(0, node);
5333 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5334 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5336 // Create some initial channels
5337 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5339 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5340 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5341 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5343 // Ensure all nodes are at the same height
5344 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5345 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5346 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5347 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5349 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5350 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5351 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5352 assert_eq!(local_txn_1[0].input.len(), 1);
5353 check_spends!(local_txn_1[0], chan_1.3);
5355 // We check funding pubkey are unique
5356 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]));
5357 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]));
5358 if from_0_funding_key_0 == from_1_funding_key_0
5359 || from_0_funding_key_0 == from_1_funding_key_1
5360 || from_0_funding_key_1 == from_1_funding_key_0
5361 || from_0_funding_key_1 == from_1_funding_key_1 {
5362 panic!("Funding pubkeys aren't unique");
5365 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5366 mine_transaction(&nodes[0], &local_txn_1[0]);
5367 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5368 check_closed_broadcast!(nodes[0], true);
5369 check_added_monitors!(nodes[0], 1);
5370 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5372 let htlc_timeout = {
5373 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5374 assert_eq!(node_txn.len(), 1);
5375 assert_eq!(node_txn[0].input.len(), 1);
5376 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5377 check_spends!(node_txn[0], local_txn_1[0]);
5381 mine_transaction(&nodes[0], &htlc_timeout);
5382 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5383 expect_payment_failed!(nodes[0], our_payment_hash, false);
5385 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5386 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5387 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5388 assert_eq!(spend_txn.len(), 3);
5389 check_spends!(spend_txn[0], local_txn_1[0]);
5390 assert_eq!(spend_txn[1].input.len(), 1);
5391 check_spends!(spend_txn[1], htlc_timeout);
5392 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5393 assert_eq!(spend_txn[2].input.len(), 2);
5394 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5395 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5396 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5400 fn test_static_output_closing_tx() {
5401 let chanmon_cfgs = create_chanmon_cfgs(2);
5402 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5403 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5404 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5406 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5408 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5409 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5411 mine_transaction(&nodes[0], &closing_tx);
5412 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5413 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5415 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5416 assert_eq!(spend_txn.len(), 1);
5417 check_spends!(spend_txn[0], closing_tx);
5419 mine_transaction(&nodes[1], &closing_tx);
5420 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5421 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5423 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5424 assert_eq!(spend_txn.len(), 1);
5425 check_spends!(spend_txn[0], closing_tx);
5428 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5429 let chanmon_cfgs = create_chanmon_cfgs(2);
5430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5433 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5435 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5437 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5438 // present in B's local commitment transaction, but none of A's commitment transactions.
5439 nodes[1].node.claim_funds(payment_preimage);
5440 check_added_monitors!(nodes[1], 1);
5441 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5443 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5444 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5445 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5447 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5448 check_added_monitors!(nodes[0], 1);
5449 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5450 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5451 check_added_monitors!(nodes[1], 1);
5453 let starting_block = nodes[1].best_block_info();
5454 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5455 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5456 connect_block(&nodes[1], &block);
5457 block.header.prev_blockhash = block.block_hash();
5459 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5460 check_closed_broadcast!(nodes[1], true);
5461 check_added_monitors!(nodes[1], 1);
5462 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5465 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5466 let chanmon_cfgs = create_chanmon_cfgs(2);
5467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5469 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5470 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5472 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5473 nodes[0].node.send_payment_with_route(&route, payment_hash,
5474 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5475 check_added_monitors!(nodes[0], 1);
5477 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5479 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5480 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5481 // to "time out" the HTLC.
5483 let starting_block = nodes[1].best_block_info();
5484 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5486 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5487 connect_block(&nodes[0], &block);
5488 block.header.prev_blockhash = block.block_hash();
5490 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5491 check_closed_broadcast!(nodes[0], true);
5492 check_added_monitors!(nodes[0], 1);
5493 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5496 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5497 let chanmon_cfgs = create_chanmon_cfgs(3);
5498 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5499 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5500 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5501 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5503 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5504 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5505 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5506 // actually revoked.
5507 let htlc_value = if use_dust { 50000 } else { 3000000 };
5508 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5509 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5510 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5511 check_added_monitors!(nodes[1], 1);
5513 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5514 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5515 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5516 check_added_monitors!(nodes[0], 1);
5517 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5518 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5519 check_added_monitors!(nodes[1], 1);
5520 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5521 check_added_monitors!(nodes[1], 1);
5522 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5524 if check_revoke_no_close {
5525 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5526 check_added_monitors!(nodes[0], 1);
5529 let starting_block = nodes[1].best_block_info();
5530 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5531 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5532 connect_block(&nodes[0], &block);
5533 block.header.prev_blockhash = block.block_hash();
5535 if !check_revoke_no_close {
5536 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5537 check_closed_broadcast!(nodes[0], true);
5538 check_added_monitors!(nodes[0], 1);
5539 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5541 expect_payment_failed!(nodes[0], our_payment_hash, true);
5545 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5546 // There are only a few cases to test here:
5547 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5548 // broadcastable commitment transactions result in channel closure,
5549 // * its included in an unrevoked-but-previous remote commitment transaction,
5550 // * its included in the latest remote or local commitment transactions.
5551 // We test each of the three possible commitment transactions individually and use both dust and
5553 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5554 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5555 // tested for at least one of the cases in other tests.
5557 fn htlc_claim_single_commitment_only_a() {
5558 do_htlc_claim_local_commitment_only(true);
5559 do_htlc_claim_local_commitment_only(false);
5561 do_htlc_claim_current_remote_commitment_only(true);
5562 do_htlc_claim_current_remote_commitment_only(false);
5566 fn htlc_claim_single_commitment_only_b() {
5567 do_htlc_claim_previous_remote_commitment_only(true, false);
5568 do_htlc_claim_previous_remote_commitment_only(false, false);
5569 do_htlc_claim_previous_remote_commitment_only(true, true);
5570 do_htlc_claim_previous_remote_commitment_only(false, true);
5575 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5576 let chanmon_cfgs = create_chanmon_cfgs(2);
5577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5579 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5580 // Force duplicate randomness for every get-random call
5581 for node in nodes.iter() {
5582 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5585 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5586 let channel_value_satoshis=10000;
5587 let push_msat=10001;
5588 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5589 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5590 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5591 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5593 // Create a second channel with the same random values. This used to panic due to a colliding
5594 // channel_id, but now panics due to a colliding outbound SCID alias.
5595 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5599 fn bolt2_open_channel_sending_node_checks_part2() {
5600 let chanmon_cfgs = create_chanmon_cfgs(2);
5601 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5602 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5603 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5605 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5606 let channel_value_satoshis=2^24;
5607 let push_msat=10001;
5608 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5610 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5611 let channel_value_satoshis=10000;
5612 // Test when push_msat is equal to 1000 * funding_satoshis.
5613 let push_msat=1000*channel_value_satoshis+1;
5614 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5616 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5617 let channel_value_satoshis=10000;
5618 let push_msat=10001;
5619 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
5620 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5621 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5623 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5624 // 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
5625 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5627 // 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.
5628 assert!(BREAKDOWN_TIMEOUT>0);
5629 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5631 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5632 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5633 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5635 // 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.
5636 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5637 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5638 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5639 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5640 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5644 fn bolt2_open_channel_sane_dust_limit() {
5645 let chanmon_cfgs = create_chanmon_cfgs(2);
5646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5648 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5650 let channel_value_satoshis=1000000;
5651 let push_msat=10001;
5652 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5653 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5654 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5655 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5657 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5658 let events = nodes[1].node.get_and_clear_pending_msg_events();
5659 let err_msg = match events[0] {
5660 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5663 _ => panic!("Unexpected event"),
5665 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5668 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5669 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5670 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5671 // is no longer affordable once it's freed.
5673 fn test_fail_holding_cell_htlc_upon_free() {
5674 let chanmon_cfgs = create_chanmon_cfgs(2);
5675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5677 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5678 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5680 // First nodes[0] generates an update_fee, setting the channel's
5681 // pending_update_fee.
5683 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5684 *feerate_lock += 20;
5686 nodes[0].node.timer_tick_occurred();
5687 check_added_monitors!(nodes[0], 1);
5689 let events = nodes[0].node.get_and_clear_pending_msg_events();
5690 assert_eq!(events.len(), 1);
5691 let (update_msg, commitment_signed) = match events[0] {
5692 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5693 (update_fee.as_ref(), commitment_signed)
5695 _ => panic!("Unexpected event"),
5698 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5700 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5701 let channel_reserve = chan_stat.channel_reserve_msat;
5702 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5703 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5705 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5706 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5707 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5709 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5710 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5711 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5712 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5713 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5715 // Flush the pending fee update.
5716 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5717 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5718 check_added_monitors!(nodes[1], 1);
5719 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5720 check_added_monitors!(nodes[0], 1);
5722 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5723 // HTLC, but now that the fee has been raised the payment will now fail, causing
5724 // us to surface its failure to the user.
5725 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5726 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5727 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);
5729 // Check that the payment failed to be sent out.
5730 let events = nodes[0].node.get_and_clear_pending_events();
5731 assert_eq!(events.len(), 2);
5733 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5734 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5735 assert_eq!(our_payment_hash.clone(), *payment_hash);
5736 assert_eq!(*payment_failed_permanently, false);
5737 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5739 _ => panic!("Unexpected event"),
5742 &Event::PaymentFailed { ref payment_hash, .. } => {
5743 assert_eq!(our_payment_hash.clone(), *payment_hash);
5745 _ => panic!("Unexpected event"),
5749 // Test that if multiple HTLCs are released from the holding cell and one is
5750 // valid but the other is no longer valid upon release, the valid HTLC can be
5751 // successfully completed while the other one fails as expected.
5753 fn test_free_and_fail_holding_cell_htlcs() {
5754 let chanmon_cfgs = create_chanmon_cfgs(2);
5755 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5756 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5757 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5758 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5760 // First nodes[0] generates an update_fee, setting the channel's
5761 // pending_update_fee.
5763 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5764 *feerate_lock += 200;
5766 nodes[0].node.timer_tick_occurred();
5767 check_added_monitors!(nodes[0], 1);
5769 let events = nodes[0].node.get_and_clear_pending_msg_events();
5770 assert_eq!(events.len(), 1);
5771 let (update_msg, commitment_signed) = match events[0] {
5772 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5773 (update_fee.as_ref(), commitment_signed)
5775 _ => panic!("Unexpected event"),
5778 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5780 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5781 let channel_reserve = chan_stat.channel_reserve_msat;
5782 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5783 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5785 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5787 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5788 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5789 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5791 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5792 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5793 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5794 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5795 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5796 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5797 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5798 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5799 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5800 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5802 // Flush the pending fee update.
5803 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5804 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5805 check_added_monitors!(nodes[1], 1);
5806 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5807 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5808 check_added_monitors!(nodes[0], 2);
5810 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5811 // but now that the fee has been raised the second payment will now fail, causing us
5812 // to surface its failure to the user. The first payment should succeed.
5813 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5814 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5815 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);
5817 // Check that the second payment failed to be sent out.
5818 let events = nodes[0].node.get_and_clear_pending_events();
5819 assert_eq!(events.len(), 2);
5821 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5822 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5823 assert_eq!(payment_hash_2.clone(), *payment_hash);
5824 assert_eq!(*payment_failed_permanently, false);
5825 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5827 _ => panic!("Unexpected event"),
5830 &Event::PaymentFailed { ref payment_hash, .. } => {
5831 assert_eq!(payment_hash_2.clone(), *payment_hash);
5833 _ => panic!("Unexpected event"),
5836 // Complete the first payment and the RAA from the fee update.
5837 let (payment_event, send_raa_event) = {
5838 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5839 assert_eq!(msgs.len(), 2);
5840 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5842 let raa = match send_raa_event {
5843 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5844 _ => panic!("Unexpected event"),
5846 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5847 check_added_monitors!(nodes[1], 1);
5848 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5849 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5850 let events = nodes[1].node.get_and_clear_pending_events();
5851 assert_eq!(events.len(), 1);
5853 Event::PendingHTLCsForwardable { .. } => {},
5854 _ => panic!("Unexpected event"),
5856 nodes[1].node.process_pending_htlc_forwards();
5857 let events = nodes[1].node.get_and_clear_pending_events();
5858 assert_eq!(events.len(), 1);
5860 Event::PaymentClaimable { .. } => {},
5861 _ => panic!("Unexpected event"),
5863 nodes[1].node.claim_funds(payment_preimage_1);
5864 check_added_monitors!(nodes[1], 1);
5865 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5867 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5868 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5869 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5870 expect_payment_sent!(nodes[0], payment_preimage_1);
5873 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5874 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5875 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5878 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5879 let chanmon_cfgs = create_chanmon_cfgs(3);
5880 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5881 // Avoid having to include routing fees in calculations
5882 let mut config = test_default_channel_config();
5883 config.channel_config.forwarding_fee_base_msat = 0;
5884 config.channel_config.forwarding_fee_proportional_millionths = 0;
5885 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5886 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5887 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5888 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5890 // First nodes[1] generates an update_fee, setting the channel's
5891 // pending_update_fee.
5893 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5894 *feerate_lock += 20;
5896 nodes[1].node.timer_tick_occurred();
5897 check_added_monitors!(nodes[1], 1);
5899 let events = nodes[1].node.get_and_clear_pending_msg_events();
5900 assert_eq!(events.len(), 1);
5901 let (update_msg, commitment_signed) = match events[0] {
5902 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5903 (update_fee.as_ref(), commitment_signed)
5905 _ => panic!("Unexpected event"),
5908 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5910 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5911 let channel_reserve = chan_stat.channel_reserve_msat;
5912 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5913 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5915 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5916 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5917 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5918 let payment_event = {
5919 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5920 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5921 check_added_monitors!(nodes[0], 1);
5923 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5924 assert_eq!(events.len(), 1);
5926 SendEvent::from_event(events.remove(0))
5928 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5929 check_added_monitors!(nodes[1], 0);
5930 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5931 expect_pending_htlcs_forwardable!(nodes[1]);
5933 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5934 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5936 // Flush the pending fee update.
5937 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5938 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5939 check_added_monitors!(nodes[2], 1);
5940 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5941 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5942 check_added_monitors!(nodes[1], 2);
5944 // A final RAA message is generated to finalize the fee update.
5945 let events = nodes[1].node.get_and_clear_pending_msg_events();
5946 assert_eq!(events.len(), 1);
5948 let raa_msg = match &events[0] {
5949 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5952 _ => panic!("Unexpected event"),
5955 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5956 check_added_monitors!(nodes[2], 1);
5957 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5959 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5960 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5961 assert_eq!(process_htlc_forwards_event.len(), 2);
5962 match &process_htlc_forwards_event[0] {
5963 &Event::PendingHTLCsForwardable { .. } => {},
5964 _ => panic!("Unexpected event"),
5967 // In response, we call ChannelManager's process_pending_htlc_forwards
5968 nodes[1].node.process_pending_htlc_forwards();
5969 check_added_monitors!(nodes[1], 1);
5971 // This causes the HTLC to be failed backwards.
5972 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5973 assert_eq!(fail_event.len(), 1);
5974 let (fail_msg, commitment_signed) = match &fail_event[0] {
5975 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5976 assert_eq!(updates.update_add_htlcs.len(), 0);
5977 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5978 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5979 assert_eq!(updates.update_fail_htlcs.len(), 1);
5980 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5982 _ => panic!("Unexpected event"),
5985 // Pass the failure messages back to nodes[0].
5986 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5989 // Complete the HTLC failure+removal process.
5990 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5991 check_added_monitors!(nodes[0], 1);
5992 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5993 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5994 check_added_monitors!(nodes[1], 2);
5995 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5996 assert_eq!(final_raa_event.len(), 1);
5997 let raa = match &final_raa_event[0] {
5998 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5999 _ => panic!("Unexpected event"),
6001 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6002 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6003 check_added_monitors!(nodes[0], 1);
6006 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6007 // 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.
6008 //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.
6011 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6012 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6013 let chanmon_cfgs = create_chanmon_cfgs(2);
6014 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6015 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6016 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6017 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6019 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6020 route.paths[0].hops[0].fee_msat = 100;
6022 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6023 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6024 ), true, APIError::ChannelUnavailable { .. }, {});
6025 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6029 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6030 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6031 let chanmon_cfgs = create_chanmon_cfgs(2);
6032 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6033 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6034 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6035 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6037 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6038 route.paths[0].hops[0].fee_msat = 0;
6039 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6040 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6041 true, APIError::ChannelUnavailable { ref err },
6042 assert_eq!(err, "Cannot send 0-msat HTLC"));
6044 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6045 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6049 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6050 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6051 let chanmon_cfgs = create_chanmon_cfgs(2);
6052 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6053 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6054 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6055 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6057 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6058 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6059 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6060 check_added_monitors!(nodes[0], 1);
6061 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6062 updates.update_add_htlcs[0].amount_msat = 0;
6064 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6065 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6066 check_closed_broadcast!(nodes[1], true).unwrap();
6067 check_added_monitors!(nodes[1], 1);
6068 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6072 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6073 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6074 //It is enforced when constructing a route.
6075 let chanmon_cfgs = create_chanmon_cfgs(2);
6076 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6077 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6078 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6079 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6081 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6082 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6083 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6084 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6085 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6086 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6087 ), true, APIError::InvalidRoute { ref err },
6088 assert_eq!(err, &"Channel CLTV overflowed?"));
6092 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6093 //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.
6094 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6095 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6096 let chanmon_cfgs = create_chanmon_cfgs(2);
6097 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6098 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6099 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6100 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6101 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6102 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6104 // Fetch a route in advance as we will be unable to once we're unable to send.
6105 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6106 for i in 0..max_accepted_htlcs {
6107 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6108 let payment_event = {
6109 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6110 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6111 check_added_monitors!(nodes[0], 1);
6113 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6114 assert_eq!(events.len(), 1);
6115 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6116 assert_eq!(htlcs[0].htlc_id, i);
6120 SendEvent::from_event(events.remove(0))
6122 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6123 check_added_monitors!(nodes[1], 0);
6124 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6126 expect_pending_htlcs_forwardable!(nodes[1]);
6127 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6129 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6130 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6131 ), true, APIError::ChannelUnavailable { .. }, {});
6133 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6137 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6138 //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.
6139 let chanmon_cfgs = create_chanmon_cfgs(2);
6140 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6141 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6142 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6143 let channel_value = 100000;
6144 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6145 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6147 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6149 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6150 // Manually create a route over our max in flight (which our router normally automatically
6152 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6153 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6154 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6155 ), true, APIError::ChannelUnavailable { .. }, {});
6156 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6158 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6161 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6163 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6164 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6165 let chanmon_cfgs = create_chanmon_cfgs(2);
6166 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6167 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6168 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6169 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6170 let htlc_minimum_msat: u64;
6172 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6173 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6174 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6175 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6178 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6179 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6180 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6181 check_added_monitors!(nodes[0], 1);
6182 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6183 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6184 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6185 assert!(nodes[1].node.list_channels().is_empty());
6186 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6187 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()));
6188 check_added_monitors!(nodes[1], 1);
6189 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6193 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6194 //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
6195 let chanmon_cfgs = create_chanmon_cfgs(2);
6196 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6197 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6198 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6199 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6201 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6202 let channel_reserve = chan_stat.channel_reserve_msat;
6203 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6204 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6205 // The 2* and +1 are for the fee spike reserve.
6206 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6208 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6209 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6210 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6211 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6212 check_added_monitors!(nodes[0], 1);
6213 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6215 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6216 // at this time channel-initiatee receivers are not required to enforce that senders
6217 // respect the fee_spike_reserve.
6218 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6219 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6221 assert!(nodes[1].node.list_channels().is_empty());
6222 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6223 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6224 check_added_monitors!(nodes[1], 1);
6225 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6229 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6230 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6231 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6232 let chanmon_cfgs = create_chanmon_cfgs(2);
6233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6235 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6236 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6238 let send_amt = 3999999;
6239 let (mut route, our_payment_hash, _, our_payment_secret) =
6240 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6241 route.paths[0].hops[0].fee_msat = send_amt;
6242 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6243 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6244 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6245 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6246 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6247 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6249 let mut msg = msgs::UpdateAddHTLC {
6253 payment_hash: our_payment_hash,
6254 cltv_expiry: htlc_cltv,
6255 onion_routing_packet: onion_packet.clone(),
6259 msg.htlc_id = i as u64;
6260 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6262 msg.htlc_id = (50) as u64;
6263 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6265 assert!(nodes[1].node.list_channels().is_empty());
6266 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6267 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6268 check_added_monitors!(nodes[1], 1);
6269 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6273 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6274 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6275 let chanmon_cfgs = create_chanmon_cfgs(2);
6276 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6277 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6278 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6279 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6281 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6282 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6283 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6284 check_added_monitors!(nodes[0], 1);
6285 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6286 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;
6287 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6289 assert!(nodes[1].node.list_channels().is_empty());
6290 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6291 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6292 check_added_monitors!(nodes[1], 1);
6293 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6297 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6298 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6299 let chanmon_cfgs = create_chanmon_cfgs(2);
6300 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6301 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6302 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6304 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6305 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6306 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6307 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6308 check_added_monitors!(nodes[0], 1);
6309 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6310 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6311 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6313 assert!(nodes[1].node.list_channels().is_empty());
6314 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6315 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6316 check_added_monitors!(nodes[1], 1);
6317 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6321 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6322 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6323 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6324 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6325 let chanmon_cfgs = create_chanmon_cfgs(2);
6326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6328 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6330 create_announced_chan_between_nodes(&nodes, 0, 1);
6331 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6332 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6333 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6334 check_added_monitors!(nodes[0], 1);
6335 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6336 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6338 //Disconnect and Reconnect
6339 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6340 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6341 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6342 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6344 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6345 assert_eq!(reestablish_1.len(), 1);
6346 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6347 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6349 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6350 assert_eq!(reestablish_2.len(), 1);
6351 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6352 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6353 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6354 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6357 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6358 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6359 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6360 check_added_monitors!(nodes[1], 1);
6361 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6363 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6365 assert!(nodes[1].node.list_channels().is_empty());
6366 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6367 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6368 check_added_monitors!(nodes[1], 1);
6369 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6373 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6374 //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.
6376 let chanmon_cfgs = create_chanmon_cfgs(2);
6377 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6378 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6379 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6380 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6381 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6382 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6383 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6385 check_added_monitors!(nodes[0], 1);
6386 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6387 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6389 let update_msg = msgs::UpdateFulfillHTLC{
6392 payment_preimage: our_payment_preimage,
6395 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6397 assert!(nodes[0].node.list_channels().is_empty());
6398 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6399 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()));
6400 check_added_monitors!(nodes[0], 1);
6401 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6405 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6406 //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.
6408 let chanmon_cfgs = create_chanmon_cfgs(2);
6409 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6410 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6411 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6412 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6414 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6415 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6416 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6417 check_added_monitors!(nodes[0], 1);
6418 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6419 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6421 let update_msg = msgs::UpdateFailHTLC{
6424 reason: msgs::OnionErrorPacket { data: Vec::new()},
6427 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6429 assert!(nodes[0].node.list_channels().is_empty());
6430 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6431 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()));
6432 check_added_monitors!(nodes[0], 1);
6433 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6437 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6438 //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.
6440 let chanmon_cfgs = create_chanmon_cfgs(2);
6441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6443 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6444 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6446 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6447 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6448 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6449 check_added_monitors!(nodes[0], 1);
6450 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6451 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6452 let update_msg = msgs::UpdateFailMalformedHTLC{
6455 sha256_of_onion: [1; 32],
6456 failure_code: 0x8000,
6459 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6461 assert!(nodes[0].node.list_channels().is_empty());
6462 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6463 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()));
6464 check_added_monitors!(nodes[0], 1);
6465 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6469 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6470 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6472 let chanmon_cfgs = create_chanmon_cfgs(2);
6473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6475 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6476 create_announced_chan_between_nodes(&nodes, 0, 1);
6478 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6480 nodes[1].node.claim_funds(our_payment_preimage);
6481 check_added_monitors!(nodes[1], 1);
6482 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6484 let events = nodes[1].node.get_and_clear_pending_msg_events();
6485 assert_eq!(events.len(), 1);
6486 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6488 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, .. } } => {
6489 assert!(update_add_htlcs.is_empty());
6490 assert_eq!(update_fulfill_htlcs.len(), 1);
6491 assert!(update_fail_htlcs.is_empty());
6492 assert!(update_fail_malformed_htlcs.is_empty());
6493 assert!(update_fee.is_none());
6494 update_fulfill_htlcs[0].clone()
6496 _ => panic!("Unexpected event"),
6500 update_fulfill_msg.htlc_id = 1;
6502 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6504 assert!(nodes[0].node.list_channels().is_empty());
6505 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6506 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6507 check_added_monitors!(nodes[0], 1);
6508 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6512 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6513 //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.
6515 let chanmon_cfgs = create_chanmon_cfgs(2);
6516 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6517 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6518 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6519 create_announced_chan_between_nodes(&nodes, 0, 1);
6521 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6523 nodes[1].node.claim_funds(our_payment_preimage);
6524 check_added_monitors!(nodes[1], 1);
6525 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6527 let events = nodes[1].node.get_and_clear_pending_msg_events();
6528 assert_eq!(events.len(), 1);
6529 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6531 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, .. } } => {
6532 assert!(update_add_htlcs.is_empty());
6533 assert_eq!(update_fulfill_htlcs.len(), 1);
6534 assert!(update_fail_htlcs.is_empty());
6535 assert!(update_fail_malformed_htlcs.is_empty());
6536 assert!(update_fee.is_none());
6537 update_fulfill_htlcs[0].clone()
6539 _ => panic!("Unexpected event"),
6543 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6545 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6547 assert!(nodes[0].node.list_channels().is_empty());
6548 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6549 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6550 check_added_monitors!(nodes[0], 1);
6551 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6555 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6556 //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.
6558 let chanmon_cfgs = create_chanmon_cfgs(2);
6559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6561 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6562 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6564 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6565 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6566 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6567 check_added_monitors!(nodes[0], 1);
6569 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6570 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6572 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6573 check_added_monitors!(nodes[1], 0);
6574 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6576 let events = nodes[1].node.get_and_clear_pending_msg_events();
6578 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6580 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, .. } } => {
6581 assert!(update_add_htlcs.is_empty());
6582 assert!(update_fulfill_htlcs.is_empty());
6583 assert!(update_fail_htlcs.is_empty());
6584 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6585 assert!(update_fee.is_none());
6586 update_fail_malformed_htlcs[0].clone()
6588 _ => panic!("Unexpected event"),
6591 update_msg.failure_code &= !0x8000;
6592 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6594 assert!(nodes[0].node.list_channels().is_empty());
6595 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6596 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6597 check_added_monitors!(nodes[0], 1);
6598 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6602 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6603 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6604 // * 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.
6606 let chanmon_cfgs = create_chanmon_cfgs(3);
6607 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6608 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6609 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6610 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6611 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6613 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6616 let mut payment_event = {
6617 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6618 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6619 check_added_monitors!(nodes[0], 1);
6620 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6621 assert_eq!(events.len(), 1);
6622 SendEvent::from_event(events.remove(0))
6624 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6625 check_added_monitors!(nodes[1], 0);
6626 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6627 expect_pending_htlcs_forwardable!(nodes[1]);
6628 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6629 assert_eq!(events_2.len(), 1);
6630 check_added_monitors!(nodes[1], 1);
6631 payment_event = SendEvent::from_event(events_2.remove(0));
6632 assert_eq!(payment_event.msgs.len(), 1);
6635 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6636 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6637 check_added_monitors!(nodes[2], 0);
6638 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6640 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6641 assert_eq!(events_3.len(), 1);
6642 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6644 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 } } => {
6645 assert!(update_add_htlcs.is_empty());
6646 assert!(update_fulfill_htlcs.is_empty());
6647 assert!(update_fail_htlcs.is_empty());
6648 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6649 assert!(update_fee.is_none());
6650 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6652 _ => panic!("Unexpected event"),
6656 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6658 check_added_monitors!(nodes[1], 0);
6659 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6660 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 }]);
6661 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6662 assert_eq!(events_4.len(), 1);
6664 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6666 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, .. } } => {
6667 assert!(update_add_htlcs.is_empty());
6668 assert!(update_fulfill_htlcs.is_empty());
6669 assert_eq!(update_fail_htlcs.len(), 1);
6670 assert!(update_fail_malformed_htlcs.is_empty());
6671 assert!(update_fee.is_none());
6673 _ => panic!("Unexpected event"),
6676 check_added_monitors!(nodes[1], 1);
6680 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6681 let chanmon_cfgs = create_chanmon_cfgs(3);
6682 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6683 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6684 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6685 create_announced_chan_between_nodes(&nodes, 0, 1);
6686 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6688 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6691 let mut payment_event = {
6692 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6693 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6694 check_added_monitors!(nodes[0], 1);
6695 SendEvent::from_node(&nodes[0])
6698 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6699 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6700 expect_pending_htlcs_forwardable!(nodes[1]);
6701 check_added_monitors!(nodes[1], 1);
6702 payment_event = SendEvent::from_node(&nodes[1]);
6703 assert_eq!(payment_event.msgs.len(), 1);
6706 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6707 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6708 check_added_monitors!(nodes[2], 0);
6709 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6711 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6712 assert_eq!(events_3.len(), 1);
6714 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6715 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6716 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6717 update_msg.failure_code |= 0x2000;
6719 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6720 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6722 _ => panic!("Unexpected event"),
6725 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6726 vec![HTLCDestination::NextHopChannel {
6727 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6728 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6729 assert_eq!(events_4.len(), 1);
6730 check_added_monitors!(nodes[1], 1);
6733 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6734 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6735 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6737 _ => panic!("Unexpected event"),
6740 let events_5 = nodes[0].node.get_and_clear_pending_events();
6741 assert_eq!(events_5.len(), 2);
6743 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6744 // the node originating the error to its next hop.
6746 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6748 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6749 assert!(is_permanent);
6750 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6752 _ => panic!("Unexpected event"),
6755 Event::PaymentFailed { payment_hash, .. } => {
6756 assert_eq!(payment_hash, our_payment_hash);
6758 _ => panic!("Unexpected event"),
6761 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6764 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6765 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6766 // 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
6767 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6769 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6770 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6773 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6774 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6776 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6777 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6779 // We route 2 dust-HTLCs between A and B
6780 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6781 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6782 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6784 // Cache one local commitment tx as previous
6785 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6787 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6788 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6789 check_added_monitors!(nodes[1], 0);
6790 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6791 check_added_monitors!(nodes[1], 1);
6793 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6794 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6795 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6796 check_added_monitors!(nodes[0], 1);
6798 // Cache one local commitment tx as lastest
6799 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6801 let events = nodes[0].node.get_and_clear_pending_msg_events();
6803 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6804 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6806 _ => panic!("Unexpected event"),
6809 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6810 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6812 _ => panic!("Unexpected event"),
6815 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6816 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6817 if announce_latest {
6818 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6820 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6823 check_closed_broadcast!(nodes[0], true);
6824 check_added_monitors!(nodes[0], 1);
6825 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6827 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6828 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6829 let events = nodes[0].node.get_and_clear_pending_events();
6830 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6831 assert_eq!(events.len(), 4);
6832 let mut first_failed = false;
6833 for event in events {
6835 Event::PaymentPathFailed { payment_hash, .. } => {
6836 if payment_hash == payment_hash_1 {
6837 assert!(!first_failed);
6838 first_failed = true;
6840 assert_eq!(payment_hash, payment_hash_2);
6843 Event::PaymentFailed { .. } => {}
6844 _ => panic!("Unexpected event"),
6850 fn test_failure_delay_dust_htlc_local_commitment() {
6851 do_test_failure_delay_dust_htlc_local_commitment(true);
6852 do_test_failure_delay_dust_htlc_local_commitment(false);
6855 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6856 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6857 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6858 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6859 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6860 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6861 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6863 let chanmon_cfgs = create_chanmon_cfgs(3);
6864 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6865 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6866 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6867 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6869 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6870 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6872 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6873 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6875 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6876 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6878 // We revoked bs_commitment_tx
6880 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6881 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6884 let mut timeout_tx = Vec::new();
6886 // We fail dust-HTLC 1 by broadcast of local commitment tx
6887 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6888 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6889 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6890 expect_payment_failed!(nodes[0], dust_hash, false);
6892 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6893 check_closed_broadcast!(nodes[0], true);
6894 check_added_monitors!(nodes[0], 1);
6895 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6896 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6897 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6898 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6899 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6900 mine_transaction(&nodes[0], &timeout_tx[0]);
6901 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6902 expect_payment_failed!(nodes[0], non_dust_hash, false);
6904 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6905 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6906 check_closed_broadcast!(nodes[0], true);
6907 check_added_monitors!(nodes[0], 1);
6908 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6909 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6911 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6912 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6913 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6914 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6915 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6916 // dust HTLC should have been failed.
6917 expect_payment_failed!(nodes[0], dust_hash, false);
6920 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6922 assert_eq!(timeout_tx[0].lock_time.0, 11);
6924 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6925 mine_transaction(&nodes[0], &timeout_tx[0]);
6926 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6927 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6928 expect_payment_failed!(nodes[0], non_dust_hash, false);
6933 fn test_sweep_outbound_htlc_failure_update() {
6934 do_test_sweep_outbound_htlc_failure_update(false, true);
6935 do_test_sweep_outbound_htlc_failure_update(false, false);
6936 do_test_sweep_outbound_htlc_failure_update(true, false);
6940 fn test_user_configurable_csv_delay() {
6941 // We test our channel constructors yield errors when we pass them absurd csv delay
6943 let mut low_our_to_self_config = UserConfig::default();
6944 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6945 let mut high_their_to_self_config = UserConfig::default();
6946 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6947 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6948 let chanmon_cfgs = create_chanmon_cfgs(2);
6949 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6950 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6951 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6953 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new_outbound()
6954 if let Err(error) = OutboundV1Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6955 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6956 &low_our_to_self_config, 0, 42)
6959 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())); },
6960 _ => panic!("Unexpected event"),
6962 } else { assert!(false) }
6964 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new_from_req()
6965 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6966 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6967 open_channel.to_self_delay = 200;
6968 if let Err(error) = InboundV1Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6969 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
6970 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6973 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())); },
6974 _ => panic!("Unexpected event"),
6976 } else { assert!(false); }
6978 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6979 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6980 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()));
6981 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6982 accept_channel.to_self_delay = 200;
6983 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6985 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6987 &ErrorAction::SendErrorMessage { ref msg } => {
6988 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()));
6989 reason_msg = msg.data.clone();
6993 } else { panic!(); }
6994 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6996 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new_from_req()
6997 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6998 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6999 open_channel.to_self_delay = 200;
7000 if let Err(error) = InboundV1Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7001 &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,
7002 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7005 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())); },
7006 _ => panic!("Unexpected event"),
7008 } else { assert!(false); }
7012 fn test_check_htlc_underpaying() {
7013 // Send payment through A -> B but A is maliciously
7014 // sending a probe payment (i.e less than expected value0
7015 // to B, B should refuse payment.
7017 let chanmon_cfgs = create_chanmon_cfgs(2);
7018 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7019 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7020 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7022 // Create some initial channels
7023 create_announced_chan_between_nodes(&nodes, 0, 1);
7025 let scorer = test_utils::TestScorer::new();
7026 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7027 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();
7028 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();
7029 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7030 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7031 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7032 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7033 check_added_monitors!(nodes[0], 1);
7035 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7036 assert_eq!(events.len(), 1);
7037 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7038 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7039 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7041 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7042 // and then will wait a second random delay before failing the HTLC back:
7043 expect_pending_htlcs_forwardable!(nodes[1]);
7044 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7046 // Node 3 is expecting payment of 100_000 but received 10_000,
7047 // it should fail htlc like we didn't know the preimage.
7048 nodes[1].node.process_pending_htlc_forwards();
7050 let events = nodes[1].node.get_and_clear_pending_msg_events();
7051 assert_eq!(events.len(), 1);
7052 let (update_fail_htlc, commitment_signed) = match events[0] {
7053 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 } } => {
7054 assert!(update_add_htlcs.is_empty());
7055 assert!(update_fulfill_htlcs.is_empty());
7056 assert_eq!(update_fail_htlcs.len(), 1);
7057 assert!(update_fail_malformed_htlcs.is_empty());
7058 assert!(update_fee.is_none());
7059 (update_fail_htlcs[0].clone(), commitment_signed)
7061 _ => panic!("Unexpected event"),
7063 check_added_monitors!(nodes[1], 1);
7065 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7066 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7068 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7069 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7070 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7071 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7075 fn test_announce_disable_channels() {
7076 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7077 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7079 let chanmon_cfgs = create_chanmon_cfgs(2);
7080 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7081 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7082 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7084 create_announced_chan_between_nodes(&nodes, 0, 1);
7085 create_announced_chan_between_nodes(&nodes, 1, 0);
7086 create_announced_chan_between_nodes(&nodes, 0, 1);
7089 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7090 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7092 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7093 nodes[0].node.timer_tick_occurred();
7095 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7096 assert_eq!(msg_events.len(), 3);
7097 let mut chans_disabled = HashMap::new();
7098 for e in msg_events {
7100 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7101 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7102 // Check that each channel gets updated exactly once
7103 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7104 panic!("Generated ChannelUpdate for wrong chan!");
7107 _ => panic!("Unexpected event"),
7111 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7112 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7114 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7115 assert_eq!(reestablish_1.len(), 3);
7116 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7117 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7119 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7120 assert_eq!(reestablish_2.len(), 3);
7122 // Reestablish chan_1
7123 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7124 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7125 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7126 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7127 // Reestablish chan_2
7128 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7129 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7130 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7131 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7132 // Reestablish chan_3
7133 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7134 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7135 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7136 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7138 for _ in 0..ENABLE_GOSSIP_TICKS {
7139 nodes[0].node.timer_tick_occurred();
7141 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7142 nodes[0].node.timer_tick_occurred();
7143 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7144 assert_eq!(msg_events.len(), 3);
7145 for e in msg_events {
7147 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7148 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7149 match chans_disabled.remove(&msg.contents.short_channel_id) {
7150 // Each update should have a higher timestamp than the previous one, replacing
7152 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7153 None => panic!("Generated ChannelUpdate for wrong chan!"),
7156 _ => panic!("Unexpected event"),
7159 // Check that each channel gets updated exactly once
7160 assert!(chans_disabled.is_empty());
7164 fn test_bump_penalty_txn_on_revoked_commitment() {
7165 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7166 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7168 let chanmon_cfgs = create_chanmon_cfgs(2);
7169 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7170 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7171 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7173 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7175 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7176 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7177 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7178 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7179 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7181 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7182 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7183 assert_eq!(revoked_txn[0].output.len(), 4);
7184 assert_eq!(revoked_txn[0].input.len(), 1);
7185 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7186 let revoked_txid = revoked_txn[0].txid();
7188 let mut penalty_sum = 0;
7189 for outp in revoked_txn[0].output.iter() {
7190 if outp.script_pubkey.is_v0_p2wsh() {
7191 penalty_sum += outp.value;
7195 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7196 let header_114 = connect_blocks(&nodes[1], 14);
7198 // Actually revoke tx by claiming a HTLC
7199 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7200 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7201 check_added_monitors!(nodes[1], 1);
7203 // One or more justice tx should have been broadcast, check it
7207 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7208 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7209 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7210 assert_eq!(node_txn[0].output.len(), 1);
7211 check_spends!(node_txn[0], revoked_txn[0]);
7212 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7213 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7214 penalty_1 = node_txn[0].txid();
7218 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7219 connect_blocks(&nodes[1], 15);
7220 let mut penalty_2 = penalty_1;
7221 let mut feerate_2 = 0;
7223 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7224 assert_eq!(node_txn.len(), 1);
7225 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7226 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7227 assert_eq!(node_txn[0].output.len(), 1);
7228 check_spends!(node_txn[0], revoked_txn[0]);
7229 penalty_2 = node_txn[0].txid();
7230 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7231 assert_ne!(penalty_2, penalty_1);
7232 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7233 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7234 // Verify 25% bump heuristic
7235 assert!(feerate_2 * 100 >= feerate_1 * 125);
7239 assert_ne!(feerate_2, 0);
7241 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7242 connect_blocks(&nodes[1], 1);
7244 let mut feerate_3 = 0;
7246 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7247 assert_eq!(node_txn.len(), 1);
7248 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7249 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7250 assert_eq!(node_txn[0].output.len(), 1);
7251 check_spends!(node_txn[0], revoked_txn[0]);
7252 penalty_3 = node_txn[0].txid();
7253 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7254 assert_ne!(penalty_3, penalty_2);
7255 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7256 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7257 // Verify 25% bump heuristic
7258 assert!(feerate_3 * 100 >= feerate_2 * 125);
7262 assert_ne!(feerate_3, 0);
7264 nodes[1].node.get_and_clear_pending_events();
7265 nodes[1].node.get_and_clear_pending_msg_events();
7269 fn test_bump_penalty_txn_on_revoked_htlcs() {
7270 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7271 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7273 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7274 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7277 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7279 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7280 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7281 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7282 let scorer = test_utils::TestScorer::new();
7283 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7284 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7285 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7286 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7287 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7288 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7289 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7290 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7292 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7293 assert_eq!(revoked_local_txn[0].input.len(), 1);
7294 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7296 // Revoke local commitment tx
7297 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7299 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7300 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7301 check_closed_broadcast!(nodes[1], true);
7302 check_added_monitors!(nodes[1], 1);
7303 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7304 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7306 let revoked_htlc_txn = {
7307 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7308 assert_eq!(txn.len(), 2);
7310 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7311 assert_eq!(txn[0].input.len(), 1);
7312 check_spends!(txn[0], revoked_local_txn[0]);
7314 assert_eq!(txn[1].input.len(), 1);
7315 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7316 assert_eq!(txn[1].output.len(), 1);
7317 check_spends!(txn[1], revoked_local_txn[0]);
7322 // Broadcast set of revoked txn on A
7323 let hash_128 = connect_blocks(&nodes[0], 40);
7324 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7325 connect_block(&nodes[0], &block_11);
7326 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7327 connect_block(&nodes[0], &block_129);
7328 let events = nodes[0].node.get_and_clear_pending_events();
7329 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7330 match events.last().unwrap() {
7331 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7332 _ => panic!("Unexpected event"),
7338 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7339 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7340 // Verify claim tx are spending revoked HTLC txn
7342 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7343 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7344 // which are included in the same block (they are broadcasted because we scan the
7345 // transactions linearly and generate claims as we go, they likely should be removed in the
7347 assert_eq!(node_txn[0].input.len(), 1);
7348 check_spends!(node_txn[0], revoked_local_txn[0]);
7349 assert_eq!(node_txn[1].input.len(), 1);
7350 check_spends!(node_txn[1], revoked_local_txn[0]);
7351 assert_eq!(node_txn[2].input.len(), 1);
7352 check_spends!(node_txn[2], revoked_local_txn[0]);
7354 // Each of the three justice transactions claim a separate (single) output of the three
7355 // available, which we check here:
7356 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7357 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7358 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7360 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7361 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7363 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7364 // output, checked above).
7365 assert_eq!(node_txn[3].input.len(), 2);
7366 assert_eq!(node_txn[3].output.len(), 1);
7367 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7369 first = node_txn[3].txid();
7370 // Store both feerates for later comparison
7371 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7372 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7373 penalty_txn = vec![node_txn[2].clone()];
7377 // Connect one more block to see if bumped penalty are issued for HTLC txn
7378 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7379 connect_block(&nodes[0], &block_130);
7380 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7381 connect_block(&nodes[0], &block_131);
7383 // Few more blocks to confirm penalty txn
7384 connect_blocks(&nodes[0], 4);
7385 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7386 let header_144 = connect_blocks(&nodes[0], 9);
7388 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7389 assert_eq!(node_txn.len(), 1);
7391 assert_eq!(node_txn[0].input.len(), 2);
7392 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7393 // Verify bumped tx is different and 25% bump heuristic
7394 assert_ne!(first, node_txn[0].txid());
7395 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7396 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7397 assert!(feerate_2 * 100 > feerate_1 * 125);
7398 let txn = vec![node_txn[0].clone()];
7402 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7403 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7404 connect_blocks(&nodes[0], 20);
7406 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7407 // We verify than no new transaction has been broadcast because previously
7408 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7409 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7410 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7411 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7412 // up bumped justice generation.
7413 assert_eq!(node_txn.len(), 0);
7416 check_closed_broadcast!(nodes[0], true);
7417 check_added_monitors!(nodes[0], 1);
7421 fn test_bump_penalty_txn_on_remote_commitment() {
7422 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7423 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7426 // Provide preimage for one
7427 // Check aggregation
7429 let chanmon_cfgs = create_chanmon_cfgs(2);
7430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7434 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7435 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7436 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7438 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7439 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7440 assert_eq!(remote_txn[0].output.len(), 4);
7441 assert_eq!(remote_txn[0].input.len(), 1);
7442 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7444 // Claim a HTLC without revocation (provide B monitor with preimage)
7445 nodes[1].node.claim_funds(payment_preimage);
7446 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7447 mine_transaction(&nodes[1], &remote_txn[0]);
7448 check_added_monitors!(nodes[1], 2);
7449 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7451 // One or more claim tx should have been broadcast, check it
7455 let feerate_timeout;
7456 let feerate_preimage;
7458 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7459 // 3 transactions including:
7460 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7461 assert_eq!(node_txn.len(), 3);
7462 assert_eq!(node_txn[0].input.len(), 1);
7463 assert_eq!(node_txn[1].input.len(), 1);
7464 assert_eq!(node_txn[2].input.len(), 1);
7465 check_spends!(node_txn[0], remote_txn[0]);
7466 check_spends!(node_txn[1], remote_txn[0]);
7467 check_spends!(node_txn[2], remote_txn[0]);
7469 preimage = node_txn[0].txid();
7470 let index = node_txn[0].input[0].previous_output.vout;
7471 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7472 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7474 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7475 (node_txn[2].clone(), node_txn[1].clone())
7477 (node_txn[1].clone(), node_txn[2].clone())
7480 preimage_bump = preimage_bump_tx;
7481 check_spends!(preimage_bump, remote_txn[0]);
7482 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7484 timeout = timeout_tx.txid();
7485 let index = timeout_tx.input[0].previous_output.vout;
7486 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7487 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7491 assert_ne!(feerate_timeout, 0);
7492 assert_ne!(feerate_preimage, 0);
7494 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7495 connect_blocks(&nodes[1], 1);
7497 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7498 assert_eq!(node_txn.len(), 1);
7499 assert_eq!(node_txn[0].input.len(), 1);
7500 assert_eq!(preimage_bump.input.len(), 1);
7501 check_spends!(node_txn[0], remote_txn[0]);
7502 check_spends!(preimage_bump, remote_txn[0]);
7504 let index = preimage_bump.input[0].previous_output.vout;
7505 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7506 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7507 assert!(new_feerate * 100 > feerate_timeout * 125);
7508 assert_ne!(timeout, preimage_bump.txid());
7510 let index = node_txn[0].input[0].previous_output.vout;
7511 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7512 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7513 assert!(new_feerate * 100 > feerate_preimage * 125);
7514 assert_ne!(preimage, node_txn[0].txid());
7519 nodes[1].node.get_and_clear_pending_events();
7520 nodes[1].node.get_and_clear_pending_msg_events();
7524 fn test_counterparty_raa_skip_no_crash() {
7525 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7526 // commitment transaction, we would have happily carried on and provided them the next
7527 // commitment transaction based on one RAA forward. This would probably eventually have led to
7528 // channel closure, but it would not have resulted in funds loss. Still, our
7529 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7530 // check simply that the channel is closed in response to such an RAA, but don't check whether
7531 // we decide to punish our counterparty for revoking their funds (as we don't currently
7533 let chanmon_cfgs = create_chanmon_cfgs(2);
7534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7536 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7537 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7539 let per_commitment_secret;
7540 let next_per_commitment_point;
7542 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7543 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7544 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7546 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7548 // Make signer believe we got a counterparty signature, so that it allows the revocation
7549 keys.get_enforcement_state().last_holder_commitment -= 1;
7550 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7552 // Must revoke without gaps
7553 keys.get_enforcement_state().last_holder_commitment -= 1;
7554 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7556 keys.get_enforcement_state().last_holder_commitment -= 1;
7557 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7558 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7561 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7562 &msgs::RevokeAndACK {
7564 per_commitment_secret,
7565 next_per_commitment_point,
7567 next_local_nonce: None,
7569 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7570 check_added_monitors!(nodes[1], 1);
7571 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7575 fn test_bump_txn_sanitize_tracking_maps() {
7576 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7577 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7579 let chanmon_cfgs = create_chanmon_cfgs(2);
7580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7582 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7584 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7585 // Lock HTLC in both directions
7586 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7587 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7589 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7590 assert_eq!(revoked_local_txn[0].input.len(), 1);
7591 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7593 // Revoke local commitment tx
7594 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7596 // Broadcast set of revoked txn on A
7597 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7598 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7599 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7601 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7602 check_closed_broadcast!(nodes[0], true);
7603 check_added_monitors!(nodes[0], 1);
7604 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7606 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7607 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7608 check_spends!(node_txn[0], revoked_local_txn[0]);
7609 check_spends!(node_txn[1], revoked_local_txn[0]);
7610 check_spends!(node_txn[2], revoked_local_txn[0]);
7611 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7615 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7616 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7618 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7619 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7620 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7625 fn test_channel_conf_timeout() {
7626 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7627 // confirm within 2016 blocks, as recommended by BOLT 2.
7628 let chanmon_cfgs = create_chanmon_cfgs(2);
7629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7631 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7633 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7635 // The outbound node should wait forever for confirmation:
7636 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7637 // copied here instead of directly referencing the constant.
7638 connect_blocks(&nodes[0], 2016);
7639 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7641 // The inbound node should fail the channel after exactly 2016 blocks
7642 connect_blocks(&nodes[1], 2015);
7643 check_added_monitors!(nodes[1], 0);
7644 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7646 connect_blocks(&nodes[1], 1);
7647 check_added_monitors!(nodes[1], 1);
7648 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7649 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7650 assert_eq!(close_ev.len(), 1);
7652 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7653 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7654 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7656 _ => panic!("Unexpected event"),
7661 fn test_override_channel_config() {
7662 let chanmon_cfgs = create_chanmon_cfgs(2);
7663 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7664 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7665 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7667 // Node0 initiates a channel to node1 using the override config.
7668 let mut override_config = UserConfig::default();
7669 override_config.channel_handshake_config.our_to_self_delay = 200;
7671 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7673 // Assert the channel created by node0 is using the override config.
7674 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7675 assert_eq!(res.channel_flags, 0);
7676 assert_eq!(res.to_self_delay, 200);
7680 fn test_override_0msat_htlc_minimum() {
7681 let mut zero_config = UserConfig::default();
7682 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7683 let chanmon_cfgs = create_chanmon_cfgs(2);
7684 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7685 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7686 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7688 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7689 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7690 assert_eq!(res.htlc_minimum_msat, 1);
7692 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7693 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7694 assert_eq!(res.htlc_minimum_msat, 1);
7698 fn test_channel_update_has_correct_htlc_maximum_msat() {
7699 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7700 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7701 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7702 // 90% of the `channel_value`.
7703 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7705 let mut config_30_percent = UserConfig::default();
7706 config_30_percent.channel_handshake_config.announced_channel = true;
7707 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7708 let mut config_50_percent = UserConfig::default();
7709 config_50_percent.channel_handshake_config.announced_channel = true;
7710 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7711 let mut config_95_percent = UserConfig::default();
7712 config_95_percent.channel_handshake_config.announced_channel = true;
7713 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7714 let mut config_100_percent = UserConfig::default();
7715 config_100_percent.channel_handshake_config.announced_channel = true;
7716 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7718 let chanmon_cfgs = create_chanmon_cfgs(4);
7719 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7720 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)]);
7721 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7723 let channel_value_satoshis = 100000;
7724 let channel_value_msat = channel_value_satoshis * 1000;
7725 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7726 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7727 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7729 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7730 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7732 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7733 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7734 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7735 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7736 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7737 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7739 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7740 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7742 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7743 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7744 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7746 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7750 fn test_manually_accept_inbound_channel_request() {
7751 let mut manually_accept_conf = UserConfig::default();
7752 manually_accept_conf.manually_accept_inbound_channels = true;
7753 let chanmon_cfgs = create_chanmon_cfgs(2);
7754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7756 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7758 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7759 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7761 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7763 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7764 // accepting the inbound channel request.
7765 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7767 let events = nodes[1].node.get_and_clear_pending_events();
7769 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7770 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7772 _ => panic!("Unexpected event"),
7775 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7776 assert_eq!(accept_msg_ev.len(), 1);
7778 match accept_msg_ev[0] {
7779 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7780 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7782 _ => panic!("Unexpected event"),
7785 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7787 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7788 assert_eq!(close_msg_ev.len(), 1);
7790 let events = nodes[1].node.get_and_clear_pending_events();
7792 Event::ChannelClosed { user_channel_id, .. } => {
7793 assert_eq!(user_channel_id, 23);
7795 _ => panic!("Unexpected event"),
7800 fn test_manually_reject_inbound_channel_request() {
7801 let mut manually_accept_conf = UserConfig::default();
7802 manually_accept_conf.manually_accept_inbound_channels = true;
7803 let chanmon_cfgs = create_chanmon_cfgs(2);
7804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7806 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7808 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7809 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7811 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7813 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7814 // rejecting the inbound channel request.
7815 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7817 let events = nodes[1].node.get_and_clear_pending_events();
7819 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7820 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7822 _ => panic!("Unexpected event"),
7825 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7826 assert_eq!(close_msg_ev.len(), 1);
7828 match close_msg_ev[0] {
7829 MessageSendEvent::HandleError { ref node_id, .. } => {
7830 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7832 _ => panic!("Unexpected event"),
7834 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7838 fn test_reject_funding_before_inbound_channel_accepted() {
7839 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7840 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7841 // the node operator before the counterparty sends a `FundingCreated` message. If a
7842 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7843 // and the channel should be closed.
7844 let mut manually_accept_conf = UserConfig::default();
7845 manually_accept_conf.manually_accept_inbound_channels = true;
7846 let chanmon_cfgs = create_chanmon_cfgs(2);
7847 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7848 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7849 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7851 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7852 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7853 let temp_channel_id = res.temporary_channel_id;
7855 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7857 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7858 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7860 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7861 nodes[1].node.get_and_clear_pending_events();
7863 // Get the `AcceptChannel` message of `nodes[1]` without calling
7864 // `ChannelManager::accept_inbound_channel`, which generates a
7865 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7866 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7867 // succeed when `nodes[0]` is passed to it.
7868 let accept_chan_msg = {
7869 let mut node_1_per_peer_lock;
7870 let mut node_1_peer_state_lock;
7871 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7872 channel.get_accept_channel_message()
7874 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7876 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7878 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7879 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7881 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7882 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7884 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7885 assert_eq!(close_msg_ev.len(), 1);
7887 let expected_err = "FundingCreated message received before the channel was accepted";
7888 match close_msg_ev[0] {
7889 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7890 assert_eq!(msg.channel_id, temp_channel_id);
7891 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7892 assert_eq!(msg.data, expected_err);
7894 _ => panic!("Unexpected event"),
7897 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7901 fn test_can_not_accept_inbound_channel_twice() {
7902 let mut manually_accept_conf = UserConfig::default();
7903 manually_accept_conf.manually_accept_inbound_channels = true;
7904 let chanmon_cfgs = create_chanmon_cfgs(2);
7905 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7906 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7907 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7909 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7910 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7912 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7914 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7915 // accepting the inbound channel request.
7916 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7918 let events = nodes[1].node.get_and_clear_pending_events();
7920 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7921 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7922 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7924 Err(APIError::APIMisuseError { err }) => {
7925 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7927 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7928 Err(_) => panic!("Unexpected Error"),
7931 _ => panic!("Unexpected event"),
7934 // Ensure that the channel wasn't closed after attempting to accept it twice.
7935 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7936 assert_eq!(accept_msg_ev.len(), 1);
7938 match accept_msg_ev[0] {
7939 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7940 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7942 _ => panic!("Unexpected event"),
7947 fn test_can_not_accept_unknown_inbound_channel() {
7948 let chanmon_cfg = create_chanmon_cfgs(2);
7949 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7950 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7951 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7953 let unknown_channel_id = [0; 32];
7954 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7956 Err(APIError::ChannelUnavailable { err }) => {
7957 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()));
7959 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7960 Err(_) => panic!("Unexpected Error"),
7965 fn test_onion_value_mpp_set_calculation() {
7966 // Test that we use the onion value `amt_to_forward` when
7967 // calculating whether we've reached the `total_msat` of an MPP
7968 // by having a routing node forward more than `amt_to_forward`
7969 // and checking that the receiving node doesn't generate
7970 // a PaymentClaimable event too early
7972 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7973 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7974 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7975 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7977 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7978 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7979 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7980 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7982 let total_msat = 100_000;
7983 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7984 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7985 let sample_path = route.paths.pop().unwrap();
7987 let mut path_1 = sample_path.clone();
7988 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7989 path_1.hops[0].short_channel_id = chan_1_id;
7990 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7991 path_1.hops[1].short_channel_id = chan_3_id;
7992 path_1.hops[1].fee_msat = 100_000;
7993 route.paths.push(path_1);
7995 let mut path_2 = sample_path.clone();
7996 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
7997 path_2.hops[0].short_channel_id = chan_2_id;
7998 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
7999 path_2.hops[1].short_channel_id = chan_4_id;
8000 path_2.hops[1].fee_msat = 1_000;
8001 route.paths.push(path_2);
8004 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8005 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8006 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8007 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8008 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8009 check_added_monitors!(nodes[0], expected_paths.len());
8011 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8012 assert_eq!(events.len(), expected_paths.len());
8015 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8016 let mut payment_event = SendEvent::from_event(ev);
8017 let mut prev_node = &nodes[0];
8019 for (idx, &node) in expected_paths[0].iter().enumerate() {
8020 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8022 if idx == 0 { // routing node
8023 let session_priv = [3; 32];
8024 let height = nodes[0].best_block_info().1;
8025 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8026 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8027 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8028 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8029 // Edit amt_to_forward to simulate the sender having set
8030 // the final amount and the routing node taking less fee
8031 onion_payloads[1].amt_to_forward = 99_000;
8032 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8033 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8036 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8037 check_added_monitors!(node, 0);
8038 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8039 expect_pending_htlcs_forwardable!(node);
8042 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8043 assert_eq!(events_2.len(), 1);
8044 check_added_monitors!(node, 1);
8045 payment_event = SendEvent::from_event(events_2.remove(0));
8046 assert_eq!(payment_event.msgs.len(), 1);
8048 let events_2 = node.node.get_and_clear_pending_events();
8049 assert!(events_2.is_empty());
8056 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8057 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8059 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8062 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8064 let routing_node_count = msat_amounts.len();
8065 let node_count = routing_node_count + 2;
8067 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8068 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8069 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8070 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8075 // Create channels for each amount
8076 let mut expected_paths = Vec::with_capacity(routing_node_count);
8077 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8078 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8079 for i in 0..routing_node_count {
8080 let routing_node = 2 + i;
8081 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8082 src_chan_ids.push(src_chan_id);
8083 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8084 dst_chan_ids.push(dst_chan_id);
8085 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8086 expected_paths.push(path);
8088 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8090 // Create a route for each amount
8091 let example_amount = 100000;
8092 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);
8093 let sample_path = route.paths.pop().unwrap();
8094 for i in 0..routing_node_count {
8095 let routing_node = 2 + i;
8096 let mut path = sample_path.clone();
8097 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8098 path.hops[0].short_channel_id = src_chan_ids[i];
8099 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8100 path.hops[1].short_channel_id = dst_chan_ids[i];
8101 path.hops[1].fee_msat = msat_amounts[i];
8102 route.paths.push(path);
8105 // Send payment with manually set total_msat
8106 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8107 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8108 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8109 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8110 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8111 check_added_monitors!(nodes[src_idx], expected_paths.len());
8113 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8114 assert_eq!(events.len(), expected_paths.len());
8115 let mut amount_received = 0;
8116 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8117 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8119 let current_path_amount = msat_amounts[path_idx];
8120 amount_received += current_path_amount;
8121 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8122 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8125 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8129 fn test_overshoot_mpp() {
8130 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8131 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8135 fn test_simple_mpp() {
8136 // Simple test of sending a multi-path payment.
8137 let chanmon_cfgs = create_chanmon_cfgs(4);
8138 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8139 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8140 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8142 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8143 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8144 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8145 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8147 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8148 let path = route.paths[0].clone();
8149 route.paths.push(path);
8150 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8151 route.paths[0].hops[0].short_channel_id = chan_1_id;
8152 route.paths[0].hops[1].short_channel_id = chan_3_id;
8153 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8154 route.paths[1].hops[0].short_channel_id = chan_2_id;
8155 route.paths[1].hops[1].short_channel_id = chan_4_id;
8156 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8157 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8161 fn test_preimage_storage() {
8162 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8163 let chanmon_cfgs = create_chanmon_cfgs(2);
8164 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8165 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8166 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8168 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8171 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8172 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8173 nodes[0].node.send_payment_with_route(&route, payment_hash,
8174 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8175 check_added_monitors!(nodes[0], 1);
8176 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8177 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8178 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8179 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8181 // Note that after leaving the above scope we have no knowledge of any arguments or return
8182 // values from previous calls.
8183 expect_pending_htlcs_forwardable!(nodes[1]);
8184 let events = nodes[1].node.get_and_clear_pending_events();
8185 assert_eq!(events.len(), 1);
8187 Event::PaymentClaimable { ref purpose, .. } => {
8189 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8190 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8192 _ => panic!("expected PaymentPurpose::InvoicePayment")
8195 _ => panic!("Unexpected event"),
8200 #[allow(deprecated)]
8201 fn test_secret_timeout() {
8202 // Simple test of payment secret storage time outs. After
8203 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8204 let chanmon_cfgs = create_chanmon_cfgs(2);
8205 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8206 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8207 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8209 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8211 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8213 // We should fail to register the same payment hash twice, at least until we've connected a
8214 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8215 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8216 assert_eq!(err, "Duplicate payment hash");
8217 } else { panic!(); }
8219 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8220 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8222 connect_block(&nodes[1], &block);
8223 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8224 assert_eq!(err, "Duplicate payment hash");
8225 } else { panic!(); }
8227 // If we then connect the second block, we should be able to register the same payment hash
8228 // again (this time getting a new payment secret).
8229 block.header.prev_blockhash = block.header.block_hash();
8230 block.header.time += 1;
8231 connect_block(&nodes[1], &block);
8232 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8233 assert_ne!(payment_secret_1, our_payment_secret);
8236 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8237 nodes[0].node.send_payment_with_route(&route, payment_hash,
8238 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8239 check_added_monitors!(nodes[0], 1);
8240 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8241 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8242 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8243 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8245 // Note that after leaving the above scope we have no knowledge of any arguments or return
8246 // values from previous calls.
8247 expect_pending_htlcs_forwardable!(nodes[1]);
8248 let events = nodes[1].node.get_and_clear_pending_events();
8249 assert_eq!(events.len(), 1);
8251 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8252 assert!(payment_preimage.is_none());
8253 assert_eq!(payment_secret, our_payment_secret);
8254 // We don't actually have the payment preimage with which to claim this payment!
8256 _ => panic!("Unexpected event"),
8261 fn test_bad_secret_hash() {
8262 // Simple test of unregistered payment hash/invalid payment secret handling
8263 let chanmon_cfgs = create_chanmon_cfgs(2);
8264 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8265 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8266 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8268 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8270 let random_payment_hash = PaymentHash([42; 32]);
8271 let random_payment_secret = PaymentSecret([43; 32]);
8272 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8273 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8275 // All the below cases should end up being handled exactly identically, so we macro the
8276 // resulting events.
8277 macro_rules! handle_unknown_invalid_payment_data {
8278 ($payment_hash: expr) => {
8279 check_added_monitors!(nodes[0], 1);
8280 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8281 let payment_event = SendEvent::from_event(events.pop().unwrap());
8282 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8283 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8285 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8286 // again to process the pending backwards-failure of the HTLC
8287 expect_pending_htlcs_forwardable!(nodes[1]);
8288 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8289 check_added_monitors!(nodes[1], 1);
8291 // We should fail the payment back
8292 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8293 match events.pop().unwrap() {
8294 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8295 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8296 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8298 _ => panic!("Unexpected event"),
8303 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8304 // Error data is the HTLC value (100,000) and current block height
8305 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8307 // Send a payment with the right payment hash but the wrong payment secret
8308 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8309 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8310 handle_unknown_invalid_payment_data!(our_payment_hash);
8311 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8313 // Send a payment with a random payment hash, but the right payment secret
8314 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8315 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8316 handle_unknown_invalid_payment_data!(random_payment_hash);
8317 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8319 // Send a payment with a random payment hash and random payment secret
8320 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8321 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8322 handle_unknown_invalid_payment_data!(random_payment_hash);
8323 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8327 fn test_update_err_monitor_lockdown() {
8328 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8329 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8330 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8333 // This scenario may happen in a watchtower setup, where watchtower process a block height
8334 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8335 // commitment at same time.
8337 let chanmon_cfgs = create_chanmon_cfgs(2);
8338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8340 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8342 // Create some initial channel
8343 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8344 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8346 // Rebalance the network to generate htlc in the two directions
8347 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8349 // Route a HTLC from node 0 to node 1 (but don't settle)
8350 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8352 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8353 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8354 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8355 let persister = test_utils::TestPersister::new();
8358 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8359 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8360 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8361 assert!(new_monitor == *monitor);
8364 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);
8365 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8368 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8369 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8370 // transaction lock time requirements here.
8371 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8372 watchtower.chain_monitor.block_connected(&block, 200);
8374 // Try to update ChannelMonitor
8375 nodes[1].node.claim_funds(preimage);
8376 check_added_monitors!(nodes[1], 1);
8377 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8379 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8380 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8381 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8383 let mut node_0_per_peer_lock;
8384 let mut node_0_peer_state_lock;
8385 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8386 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8387 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8388 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8389 } else { assert!(false); }
8391 // Our local monitor is in-sync and hasn't processed yet timeout
8392 check_added_monitors!(nodes[0], 1);
8393 let events = nodes[0].node.get_and_clear_pending_events();
8394 assert_eq!(events.len(), 1);
8398 fn test_concurrent_monitor_claim() {
8399 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8400 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8401 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8402 // state N+1 confirms. Alice claims output from state N+1.
8404 let chanmon_cfgs = create_chanmon_cfgs(2);
8405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8407 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8409 // Create some initial channel
8410 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8411 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8413 // Rebalance the network to generate htlc in the two directions
8414 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8416 // Route a HTLC from node 0 to node 1 (but don't settle)
8417 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8419 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8420 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8421 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8422 let persister = test_utils::TestPersister::new();
8423 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8424 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8426 let watchtower_alice = {
8428 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8429 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8430 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8431 assert!(new_monitor == *monitor);
8434 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8435 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8438 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8439 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8440 // requirements here.
8441 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8442 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8443 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8445 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8447 let mut txn = alice_broadcaster.txn_broadcast();
8448 assert_eq!(txn.len(), 2);
8452 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8453 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8454 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8455 let persister = test_utils::TestPersister::new();
8456 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8457 let watchtower_bob = {
8459 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8460 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8461 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8462 assert!(new_monitor == *monitor);
8465 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8466 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8469 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8471 // Route another payment to generate another update with still previous HTLC pending
8472 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8473 nodes[1].node.send_payment_with_route(&route, payment_hash,
8474 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8475 check_added_monitors!(nodes[1], 1);
8477 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8478 assert_eq!(updates.update_add_htlcs.len(), 1);
8479 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8481 let mut node_0_per_peer_lock;
8482 let mut node_0_peer_state_lock;
8483 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8484 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8485 // Watchtower Alice should already have seen the block and reject the update
8486 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8487 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8488 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8489 } else { assert!(false); }
8491 // Our local monitor is in-sync and hasn't processed yet timeout
8492 check_added_monitors!(nodes[0], 1);
8494 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8495 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8497 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8500 let mut txn = bob_broadcaster.txn_broadcast();
8501 assert_eq!(txn.len(), 2);
8502 bob_state_y = txn.remove(0);
8505 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8506 let height = HTLC_TIMEOUT_BROADCAST + 1;
8507 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8508 check_closed_broadcast(&nodes[0], 1, true);
8509 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8510 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8511 check_added_monitors(&nodes[0], 1);
8513 let htlc_txn = alice_broadcaster.txn_broadcast();
8514 assert_eq!(htlc_txn.len(), 2);
8515 check_spends!(htlc_txn[0], bob_state_y);
8516 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8517 // it. However, she should, because it now has an invalid parent.
8518 check_spends!(htlc_txn[1], alice_state);
8523 fn test_pre_lockin_no_chan_closed_update() {
8524 // Test that if a peer closes a channel in response to a funding_created message we don't
8525 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8528 // Doing so would imply a channel monitor update before the initial channel monitor
8529 // registration, violating our API guarantees.
8531 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8532 // then opening a second channel with the same funding output as the first (which is not
8533 // rejected because the first channel does not exist in the ChannelManager) and closing it
8534 // before receiving funding_signed.
8535 let chanmon_cfgs = create_chanmon_cfgs(2);
8536 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8537 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8538 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8540 // Create an initial channel
8541 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8542 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8543 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8544 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8545 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8547 // Move the first channel through the funding flow...
8548 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8550 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8551 check_added_monitors!(nodes[0], 0);
8553 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8554 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8555 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8556 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8557 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8561 fn test_htlc_no_detection() {
8562 // This test is a mutation to underscore the detection logic bug we had
8563 // before #653. HTLC value routed is above the remaining balance, thus
8564 // inverting HTLC and `to_remote` output. HTLC will come second and
8565 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8566 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8567 // outputs order detection for correct spending children filtring.
8569 let chanmon_cfgs = create_chanmon_cfgs(2);
8570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8572 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8574 // Create some initial channels
8575 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8577 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8578 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8579 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8580 assert_eq!(local_txn[0].input.len(), 1);
8581 assert_eq!(local_txn[0].output.len(), 3);
8582 check_spends!(local_txn[0], chan_1.3);
8584 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8585 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8586 connect_block(&nodes[0], &block);
8587 // We deliberately connect the local tx twice as this should provoke a failure calling
8588 // this test before #653 fix.
8589 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8590 check_closed_broadcast!(nodes[0], true);
8591 check_added_monitors!(nodes[0], 1);
8592 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8593 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8595 let htlc_timeout = {
8596 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8597 assert_eq!(node_txn.len(), 1);
8598 assert_eq!(node_txn[0].input.len(), 1);
8599 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8600 check_spends!(node_txn[0], local_txn[0]);
8604 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8605 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8606 expect_payment_failed!(nodes[0], our_payment_hash, false);
8609 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8610 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8611 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8612 // Carol, Alice would be the upstream node, and Carol the downstream.)
8614 // Steps of the test:
8615 // 1) Alice sends a HTLC to Carol through Bob.
8616 // 2) Carol doesn't settle the HTLC.
8617 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8618 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8619 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8620 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8621 // 5) Carol release the preimage to Bob off-chain.
8622 // 6) Bob claims the offered output on the broadcasted commitment.
8623 let chanmon_cfgs = create_chanmon_cfgs(3);
8624 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8625 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8626 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8628 // Create some initial channels
8629 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8630 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8632 // Steps (1) and (2):
8633 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8634 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8636 // Check that Alice's commitment transaction now contains an output for this HTLC.
8637 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8638 check_spends!(alice_txn[0], chan_ab.3);
8639 assert_eq!(alice_txn[0].output.len(), 2);
8640 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8641 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8642 assert_eq!(alice_txn.len(), 2);
8644 // Steps (3) and (4):
8645 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8646 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8647 let mut force_closing_node = 0; // Alice force-closes
8648 let mut counterparty_node = 1; // Bob if Alice force-closes
8651 if !broadcast_alice {
8652 force_closing_node = 1;
8653 counterparty_node = 0;
8655 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8656 check_closed_broadcast!(nodes[force_closing_node], true);
8657 check_added_monitors!(nodes[force_closing_node], 1);
8658 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8659 if go_onchain_before_fulfill {
8660 let txn_to_broadcast = match broadcast_alice {
8661 true => alice_txn.clone(),
8662 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8664 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8665 if broadcast_alice {
8666 check_closed_broadcast!(nodes[1], true);
8667 check_added_monitors!(nodes[1], 1);
8668 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8673 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8674 // process of removing the HTLC from their commitment transactions.
8675 nodes[2].node.claim_funds(payment_preimage);
8676 check_added_monitors!(nodes[2], 1);
8677 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8679 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8680 assert!(carol_updates.update_add_htlcs.is_empty());
8681 assert!(carol_updates.update_fail_htlcs.is_empty());
8682 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8683 assert!(carol_updates.update_fee.is_none());
8684 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8686 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8687 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8688 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8689 if !go_onchain_before_fulfill && broadcast_alice {
8690 let events = nodes[1].node.get_and_clear_pending_msg_events();
8691 assert_eq!(events.len(), 1);
8693 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8694 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8696 _ => panic!("Unexpected event"),
8699 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8700 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8701 // Carol<->Bob's updated commitment transaction info.
8702 check_added_monitors!(nodes[1], 2);
8704 let events = nodes[1].node.get_and_clear_pending_msg_events();
8705 assert_eq!(events.len(), 2);
8706 let bob_revocation = match events[0] {
8707 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8708 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8711 _ => panic!("Unexpected event"),
8713 let bob_updates = match events[1] {
8714 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8715 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8718 _ => panic!("Unexpected event"),
8721 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8722 check_added_monitors!(nodes[2], 1);
8723 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8724 check_added_monitors!(nodes[2], 1);
8726 let events = nodes[2].node.get_and_clear_pending_msg_events();
8727 assert_eq!(events.len(), 1);
8728 let carol_revocation = match events[0] {
8729 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8730 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8733 _ => panic!("Unexpected event"),
8735 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8736 check_added_monitors!(nodes[1], 1);
8738 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8739 // here's where we put said channel's commitment tx on-chain.
8740 let mut txn_to_broadcast = alice_txn.clone();
8741 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8742 if !go_onchain_before_fulfill {
8743 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8744 // If Bob was the one to force-close, he will have already passed these checks earlier.
8745 if broadcast_alice {
8746 check_closed_broadcast!(nodes[1], true);
8747 check_added_monitors!(nodes[1], 1);
8748 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8750 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8751 if broadcast_alice {
8752 assert_eq!(bob_txn.len(), 1);
8753 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8755 assert_eq!(bob_txn.len(), 2);
8756 check_spends!(bob_txn[0], chan_ab.3);
8761 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8762 // broadcasted commitment transaction.
8764 let script_weight = match broadcast_alice {
8765 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8766 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8768 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8769 // Bob force-closed and broadcasts the commitment transaction along with a
8770 // HTLC-output-claiming transaction.
8771 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8772 if broadcast_alice {
8773 assert_eq!(bob_txn.len(), 1);
8774 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8775 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8777 assert_eq!(bob_txn.len(), 2);
8778 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8779 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8785 fn test_onchain_htlc_settlement_after_close() {
8786 do_test_onchain_htlc_settlement_after_close(true, true);
8787 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8788 do_test_onchain_htlc_settlement_after_close(true, false);
8789 do_test_onchain_htlc_settlement_after_close(false, false);
8793 fn test_duplicate_temporary_channel_id_from_different_peers() {
8794 // Tests that we can accept two different `OpenChannel` requests with the same
8795 // `temporary_channel_id`, as long as they are from different peers.
8796 let chanmon_cfgs = create_chanmon_cfgs(3);
8797 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8798 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8799 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8801 // Create an first channel channel
8802 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8803 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8805 // Create an second channel
8806 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8807 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8809 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8810 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8811 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8813 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8814 // `temporary_channel_id` as they are from different peers.
8815 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8817 let events = nodes[0].node.get_and_clear_pending_msg_events();
8818 assert_eq!(events.len(), 1);
8820 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8821 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8822 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8824 _ => panic!("Unexpected event"),
8828 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8830 let events = nodes[0].node.get_and_clear_pending_msg_events();
8831 assert_eq!(events.len(), 1);
8833 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8834 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8835 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8837 _ => panic!("Unexpected event"),
8843 fn test_duplicate_chan_id() {
8844 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8845 // already open we reject it and keep the old channel.
8847 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8848 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8849 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8850 // updating logic for the existing channel.
8851 let chanmon_cfgs = create_chanmon_cfgs(2);
8852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8856 // Create an initial channel
8857 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8858 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8859 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8860 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()));
8862 // Try to create a second channel with the same temporary_channel_id as the first and check
8863 // that it is rejected.
8864 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8866 let events = nodes[1].node.get_and_clear_pending_msg_events();
8867 assert_eq!(events.len(), 1);
8869 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8870 // Technically, at this point, nodes[1] would be justified in thinking both the
8871 // first (valid) and second (invalid) channels are closed, given they both have
8872 // the same non-temporary channel_id. However, currently we do not, so we just
8873 // move forward with it.
8874 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8875 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8877 _ => panic!("Unexpected event"),
8881 // Move the first channel through the funding flow...
8882 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8884 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8885 check_added_monitors!(nodes[0], 0);
8887 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8888 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8890 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8891 assert_eq!(added_monitors.len(), 1);
8892 assert_eq!(added_monitors[0].0, funding_output);
8893 added_monitors.clear();
8895 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8897 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8899 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8900 let channel_id = funding_outpoint.to_channel_id();
8902 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8905 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8906 // Technically this is allowed by the spec, but we don't support it and there's little reason
8907 // to. Still, it shouldn't cause any other issues.
8908 open_chan_msg.temporary_channel_id = channel_id;
8909 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8911 let events = nodes[1].node.get_and_clear_pending_msg_events();
8912 assert_eq!(events.len(), 1);
8914 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8915 // Technically, at this point, nodes[1] would be justified in thinking both
8916 // channels are closed, but currently we do not, so we just move forward with it.
8917 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8918 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8920 _ => panic!("Unexpected event"),
8924 // Now try to create a second channel which has a duplicate funding output.
8925 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8926 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8927 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8928 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()));
8929 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8931 let funding_created = {
8932 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8933 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8934 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8935 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8936 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8937 // channelmanager in a possibly nonsense state instead).
8938 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8939 let logger = test_utils::TestLogger::new();
8940 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8942 check_added_monitors!(nodes[0], 0);
8943 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8944 // At this point we'll look up if the channel_id is present and immediately fail the channel
8945 // without trying to persist the `ChannelMonitor`.
8946 check_added_monitors!(nodes[1], 0);
8948 // ...still, nodes[1] will reject the duplicate channel.
8950 let events = nodes[1].node.get_and_clear_pending_msg_events();
8951 assert_eq!(events.len(), 1);
8953 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8954 // Technically, at this point, nodes[1] would be justified in thinking both
8955 // channels are closed, but currently we do not, so we just move forward with it.
8956 assert_eq!(msg.channel_id, channel_id);
8957 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8959 _ => panic!("Unexpected event"),
8963 // finally, finish creating the original channel and send a payment over it to make sure
8964 // everything is functional.
8965 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8967 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8968 assert_eq!(added_monitors.len(), 1);
8969 assert_eq!(added_monitors[0].0, funding_output);
8970 added_monitors.clear();
8972 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8974 let events_4 = nodes[0].node.get_and_clear_pending_events();
8975 assert_eq!(events_4.len(), 0);
8976 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8977 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8979 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8980 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8981 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8983 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8987 fn test_error_chans_closed() {
8988 // Test that we properly handle error messages, closing appropriate channels.
8990 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8991 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8992 // we can test various edge cases around it to ensure we don't regress.
8993 let chanmon_cfgs = create_chanmon_cfgs(3);
8994 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8995 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8996 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8998 // Create some initial channels
8999 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9000 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9001 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9003 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9004 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9005 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9007 // Closing a channel from a different peer has no effect
9008 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9009 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9011 // Closing one channel doesn't impact others
9012 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9013 check_added_monitors!(nodes[0], 1);
9014 check_closed_broadcast!(nodes[0], false);
9015 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9016 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9017 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9018 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);
9019 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);
9021 // A null channel ID should close all channels
9022 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9023 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9024 check_added_monitors!(nodes[0], 2);
9025 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9026 let events = nodes[0].node.get_and_clear_pending_msg_events();
9027 assert_eq!(events.len(), 2);
9029 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9030 assert_eq!(msg.contents.flags & 2, 2);
9032 _ => panic!("Unexpected event"),
9035 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9036 assert_eq!(msg.contents.flags & 2, 2);
9038 _ => panic!("Unexpected event"),
9040 // Note that at this point users of a standard PeerHandler will end up calling
9041 // peer_disconnected.
9042 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9043 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9045 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9046 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9047 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9051 fn test_invalid_funding_tx() {
9052 // Test that we properly handle invalid funding transactions sent to us from a peer.
9054 // Previously, all other major lightning implementations had failed to properly sanitize
9055 // funding transactions from their counterparties, leading to a multi-implementation critical
9056 // security vulnerability (though we always sanitized properly, we've previously had
9057 // un-released crashes in the sanitization process).
9059 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9060 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9061 // gave up on it. We test this here by generating such a transaction.
9062 let chanmon_cfgs = create_chanmon_cfgs(2);
9063 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9064 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9065 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9067 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9068 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()));
9069 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()));
9071 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9073 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9074 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9075 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9077 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9078 let wit_program_script: Script = wit_program.into();
9079 for output in tx.output.iter_mut() {
9080 // Make the confirmed funding transaction have a bogus script_pubkey
9081 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9084 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9085 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()));
9086 check_added_monitors!(nodes[1], 1);
9087 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9089 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()));
9090 check_added_monitors!(nodes[0], 1);
9091 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9093 let events_1 = nodes[0].node.get_and_clear_pending_events();
9094 assert_eq!(events_1.len(), 0);
9096 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9097 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9098 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9100 let expected_err = "funding tx had wrong script/value or output index";
9101 confirm_transaction_at(&nodes[1], &tx, 1);
9102 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9103 check_added_monitors!(nodes[1], 1);
9104 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9105 assert_eq!(events_2.len(), 1);
9106 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9107 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9108 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9109 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9110 } else { panic!(); }
9111 } else { panic!(); }
9112 assert_eq!(nodes[1].node.list_channels().len(), 0);
9114 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9115 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9116 // as its not 32 bytes long.
9117 let mut spend_tx = Transaction {
9118 version: 2i32, lock_time: PackedLockTime::ZERO,
9119 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9120 previous_output: BitcoinOutPoint {
9124 script_sig: Script::new(),
9125 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9126 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9128 output: vec![TxOut {
9130 script_pubkey: Script::new(),
9133 check_spends!(spend_tx, tx);
9134 mine_transaction(&nodes[1], &spend_tx);
9137 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9138 // In the first version of the chain::Confirm interface, after a refactor was made to not
9139 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9140 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9141 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9142 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9143 // spending transaction until height N+1 (or greater). This was due to the way
9144 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9145 // spending transaction at the height the input transaction was confirmed at, not whether we
9146 // should broadcast a spending transaction at the current height.
9147 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9148 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9149 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9150 // until we learned about an additional block.
9152 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9153 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9154 let chanmon_cfgs = create_chanmon_cfgs(3);
9155 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9156 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9157 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9158 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9160 create_announced_chan_between_nodes(&nodes, 0, 1);
9161 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9162 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9163 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9164 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9166 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9167 check_closed_broadcast!(nodes[1], true);
9168 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9169 check_added_monitors!(nodes[1], 1);
9170 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9171 assert_eq!(node_txn.len(), 1);
9173 let conf_height = nodes[1].best_block_info().1;
9174 if !test_height_before_timelock {
9175 connect_blocks(&nodes[1], 24 * 6);
9177 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9178 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9179 if test_height_before_timelock {
9180 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9181 // generate any events or broadcast any transactions
9182 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9183 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9185 // We should broadcast an HTLC transaction spending our funding transaction first
9186 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9187 assert_eq!(spending_txn.len(), 2);
9188 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9189 check_spends!(spending_txn[1], node_txn[0]);
9190 // We should also generate a SpendableOutputs event with the to_self output (as its
9192 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9193 assert_eq!(descriptor_spend_txn.len(), 1);
9195 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9196 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9197 // additional block built on top of the current chain.
9198 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9199 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9200 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 }]);
9201 check_added_monitors!(nodes[1], 1);
9203 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9204 assert!(updates.update_add_htlcs.is_empty());
9205 assert!(updates.update_fulfill_htlcs.is_empty());
9206 assert_eq!(updates.update_fail_htlcs.len(), 1);
9207 assert!(updates.update_fail_malformed_htlcs.is_empty());
9208 assert!(updates.update_fee.is_none());
9209 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9210 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9211 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9216 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9217 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9218 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9221 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9222 let chanmon_cfgs = create_chanmon_cfgs(2);
9223 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9224 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9225 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9227 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9229 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9230 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9231 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9233 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9236 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9237 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9238 check_added_monitors!(nodes[0], 1);
9239 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9240 assert_eq!(events.len(), 1);
9241 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9242 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9243 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9245 expect_pending_htlcs_forwardable!(nodes[1]);
9246 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9249 // Note that we use a different PaymentId here to allow us to duplicativly pay
9250 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9251 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9252 check_added_monitors!(nodes[0], 1);
9253 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9254 assert_eq!(events.len(), 1);
9255 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9256 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9257 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9258 // At this point, nodes[1] would notice it has too much value for the payment. It will
9259 // assume the second is a privacy attack (no longer particularly relevant
9260 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9261 // the first HTLC delivered above.
9264 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9265 nodes[1].node.process_pending_htlc_forwards();
9267 if test_for_second_fail_panic {
9268 // Now we go fail back the first HTLC from the user end.
9269 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9271 let expected_destinations = vec![
9272 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9273 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9275 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9276 nodes[1].node.process_pending_htlc_forwards();
9278 check_added_monitors!(nodes[1], 1);
9279 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9280 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9282 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9283 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9284 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9286 let failure_events = nodes[0].node.get_and_clear_pending_events();
9287 assert_eq!(failure_events.len(), 4);
9288 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9289 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9290 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9291 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9293 // Let the second HTLC fail and claim the first
9294 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9295 nodes[1].node.process_pending_htlc_forwards();
9297 check_added_monitors!(nodes[1], 1);
9298 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9299 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9300 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9302 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9304 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9309 fn test_dup_htlc_second_fail_panic() {
9310 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9311 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9312 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9313 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9314 do_test_dup_htlc_second_rejected(true);
9318 fn test_dup_htlc_second_rejected() {
9319 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9320 // simply reject the second HTLC but are still able to claim the first HTLC.
9321 do_test_dup_htlc_second_rejected(false);
9325 fn test_inconsistent_mpp_params() {
9326 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9327 // such HTLC and allow the second to stay.
9328 let chanmon_cfgs = create_chanmon_cfgs(4);
9329 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9330 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9331 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9333 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9334 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9335 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9336 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9338 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9339 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9340 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9341 assert_eq!(route.paths.len(), 2);
9342 route.paths.sort_by(|path_a, _| {
9343 // Sort the path so that the path through nodes[1] comes first
9344 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9345 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9348 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9350 let cur_height = nodes[0].best_block_info().1;
9351 let payment_id = PaymentId([42; 32]);
9353 let session_privs = {
9354 // We create a fake route here so that we start with three pending HTLCs, which we'll
9355 // ultimately have, just not right away.
9356 let mut dup_route = route.clone();
9357 dup_route.paths.push(route.paths[1].clone());
9358 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9359 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9361 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9362 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9363 &None, session_privs[0]).unwrap();
9364 check_added_monitors!(nodes[0], 1);
9367 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9368 assert_eq!(events.len(), 1);
9369 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9371 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9373 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9374 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9375 check_added_monitors!(nodes[0], 1);
9378 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9379 assert_eq!(events.len(), 1);
9380 let payment_event = SendEvent::from_event(events.pop().unwrap());
9382 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9383 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9385 expect_pending_htlcs_forwardable!(nodes[2]);
9386 check_added_monitors!(nodes[2], 1);
9388 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9389 assert_eq!(events.len(), 1);
9390 let payment_event = SendEvent::from_event(events.pop().unwrap());
9392 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9393 check_added_monitors!(nodes[3], 0);
9394 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9396 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9397 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9398 // post-payment_secrets) and fail back the new HTLC.
9400 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9401 nodes[3].node.process_pending_htlc_forwards();
9402 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9403 nodes[3].node.process_pending_htlc_forwards();
9405 check_added_monitors!(nodes[3], 1);
9407 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9408 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9409 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9411 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 }]);
9412 check_added_monitors!(nodes[2], 1);
9414 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9415 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9416 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9418 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9420 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9421 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9422 &None, session_privs[2]).unwrap();
9423 check_added_monitors!(nodes[0], 1);
9425 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9426 assert_eq!(events.len(), 1);
9427 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9429 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9430 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9434 fn test_keysend_payments_to_public_node() {
9435 let chanmon_cfgs = create_chanmon_cfgs(2);
9436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9438 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9440 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9441 let network_graph = nodes[0].network_graph.clone();
9442 let payer_pubkey = nodes[0].node.get_our_node_id();
9443 let payee_pubkey = nodes[1].node.get_our_node_id();
9444 let route_params = RouteParameters {
9445 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9446 final_value_msat: 10000,
9448 let scorer = test_utils::TestScorer::new();
9449 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9450 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9452 let test_preimage = PaymentPreimage([42; 32]);
9453 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9454 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9455 check_added_monitors!(nodes[0], 1);
9456 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9457 assert_eq!(events.len(), 1);
9458 let event = events.pop().unwrap();
9459 let path = vec![&nodes[1]];
9460 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9461 claim_payment(&nodes[0], &path, test_preimage);
9465 fn test_keysend_payments_to_private_node() {
9466 let chanmon_cfgs = create_chanmon_cfgs(2);
9467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9471 let payer_pubkey = nodes[0].node.get_our_node_id();
9472 let payee_pubkey = nodes[1].node.get_our_node_id();
9474 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9475 let route_params = RouteParameters {
9476 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9477 final_value_msat: 10000,
9479 let network_graph = nodes[0].network_graph.clone();
9480 let first_hops = nodes[0].node.list_usable_channels();
9481 let scorer = test_utils::TestScorer::new();
9482 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9483 let route = find_route(
9484 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9485 nodes[0].logger, &scorer, &(), &random_seed_bytes
9488 let test_preimage = PaymentPreimage([42; 32]);
9489 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9490 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9491 check_added_monitors!(nodes[0], 1);
9492 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9493 assert_eq!(events.len(), 1);
9494 let event = events.pop().unwrap();
9495 let path = vec![&nodes[1]];
9496 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9497 claim_payment(&nodes[0], &path, test_preimage);
9501 fn test_double_partial_claim() {
9502 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9503 // time out, the sender resends only some of the MPP parts, then the user processes the
9504 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9506 let chanmon_cfgs = create_chanmon_cfgs(4);
9507 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9508 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9509 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9511 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9512 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9513 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9514 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9516 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9517 assert_eq!(route.paths.len(), 2);
9518 route.paths.sort_by(|path_a, _| {
9519 // Sort the path so that the path through nodes[1] comes first
9520 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9521 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9524 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9525 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9526 // amount of time to respond to.
9528 // Connect some blocks to time out the payment
9529 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9530 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9532 let failed_destinations = vec![
9533 HTLCDestination::FailedPayment { payment_hash },
9534 HTLCDestination::FailedPayment { payment_hash },
9536 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9538 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9540 // nodes[1] now retries one of the two paths...
9541 nodes[0].node.send_payment_with_route(&route, payment_hash,
9542 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9543 check_added_monitors!(nodes[0], 2);
9545 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9546 assert_eq!(events.len(), 2);
9547 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9548 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9550 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9551 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9552 nodes[3].node.claim_funds(payment_preimage);
9553 check_added_monitors!(nodes[3], 0);
9554 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9557 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9558 #[derive(Clone, Copy, PartialEq)]
9559 enum ExposureEvent {
9560 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9562 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9564 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9565 AtUpdateFeeOutbound,
9568 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9569 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9572 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9573 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9574 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9575 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9576 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9577 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9578 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9579 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9581 let chanmon_cfgs = create_chanmon_cfgs(2);
9582 let mut config = test_default_channel_config();
9583 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9586 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9588 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9589 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9590 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9591 open_channel.max_accepted_htlcs = 60;
9593 open_channel.dust_limit_satoshis = 546;
9595 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9596 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9597 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9599 let opt_anchors = false;
9601 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9604 let mut node_0_per_peer_lock;
9605 let mut node_0_peer_state_lock;
9606 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9607 chan.context.holder_dust_limit_satoshis = 546;
9610 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9611 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()));
9612 check_added_monitors!(nodes[1], 1);
9613 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9615 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()));
9616 check_added_monitors!(nodes[0], 1);
9617 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9619 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9620 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9621 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9623 // Fetch a route in advance as we will be unable to once we're unable to send.
9624 let (mut route, payment_hash, _, payment_secret) =
9625 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9627 let dust_buffer_feerate = {
9628 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9629 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9630 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9631 chan.context.get_dust_buffer_feerate(None) as u64
9633 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;
9634 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9636 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;
9637 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9639 let dust_htlc_on_counterparty_tx: u64 = 4;
9640 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9643 if dust_outbound_balance {
9644 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9645 // Outbound dust balance: 4372 sats
9646 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9647 for _ in 0..dust_outbound_htlc_on_holder_tx {
9648 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9649 nodes[0].node.send_payment_with_route(&route, payment_hash,
9650 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9653 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9654 // Inbound dust balance: 4372 sats
9655 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9656 for _ in 0..dust_inbound_htlc_on_holder_tx {
9657 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9661 if dust_outbound_balance {
9662 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9663 // Outbound dust balance: 5000 sats
9664 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9665 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9666 nodes[0].node.send_payment_with_route(&route, payment_hash,
9667 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9670 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9671 // Inbound dust balance: 5000 sats
9672 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9673 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9678 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9679 route.paths[0].hops.last_mut().unwrap().fee_msat =
9680 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9681 // With default dust exposure: 5000 sats
9683 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9684 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9685 ), true, APIError::ChannelUnavailable { .. }, {});
9687 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9688 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9689 ), true, APIError::ChannelUnavailable { .. }, {});
9691 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9692 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 });
9693 nodes[1].node.send_payment_with_route(&route, payment_hash,
9694 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9695 check_added_monitors!(nodes[1], 1);
9696 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9697 assert_eq!(events.len(), 1);
9698 let payment_event = SendEvent::from_event(events.remove(0));
9699 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9700 // With default dust exposure: 5000 sats
9702 // Outbound dust balance: 6399 sats
9703 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9704 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9705 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);
9707 // Outbound dust balance: 5200 sats
9708 nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9709 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9710 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 1,
9711 config.channel_config.max_dust_htlc_exposure_msat), 1);
9713 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9714 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9715 nodes[0].node.send_payment_with_route(&route, payment_hash,
9716 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9718 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9719 *feerate_lock = *feerate_lock * 10;
9721 nodes[0].node.timer_tick_occurred();
9722 check_added_monitors!(nodes[0], 1);
9723 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9726 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9727 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9728 added_monitors.clear();
9732 fn test_max_dust_htlc_exposure() {
9733 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9734 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9735 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9736 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9737 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9738 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9739 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9740 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9741 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9742 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9743 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9744 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9748 fn test_non_final_funding_tx() {
9749 let chanmon_cfgs = create_chanmon_cfgs(2);
9750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9752 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9754 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9755 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9756 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9757 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9758 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9760 let best_height = nodes[0].node.best_block.read().unwrap().height();
9762 let chan_id = *nodes[0].network_chan_count.borrow();
9763 let events = nodes[0].node.get_and_clear_pending_events();
9764 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9765 assert_eq!(events.len(), 1);
9766 let mut tx = match events[0] {
9767 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9768 // Timelock the transaction _beyond_ the best client height + 1.
9769 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9770 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9773 _ => panic!("Unexpected event"),
9775 // Transaction should fail as it's evaluated as non-final for propagation.
9776 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9777 Err(APIError::APIMisuseError { err }) => {
9778 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9783 // However, transaction should be accepted if it's in a +1 headroom from best block.
9784 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9785 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9786 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9790 fn accept_busted_but_better_fee() {
9791 // If a peer sends us a fee update that is too low, but higher than our previous channel
9792 // feerate, we should accept it. In the future we may want to consider closing the channel
9793 // later, but for now we only accept the update.
9794 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9795 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9796 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9797 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9799 create_chan_between_nodes(&nodes[0], &nodes[1]);
9801 // Set nodes[1] to expect 5,000 sat/kW.
9803 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9804 *feerate_lock = 5000;
9807 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9809 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9810 *feerate_lock = 1000;
9812 nodes[0].node.timer_tick_occurred();
9813 check_added_monitors!(nodes[0], 1);
9815 let events = nodes[0].node.get_and_clear_pending_msg_events();
9816 assert_eq!(events.len(), 1);
9818 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9819 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9820 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9822 _ => panic!("Unexpected event"),
9825 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9828 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9829 *feerate_lock = 2000;
9831 nodes[0].node.timer_tick_occurred();
9832 check_added_monitors!(nodes[0], 1);
9834 let events = nodes[0].node.get_and_clear_pending_msg_events();
9835 assert_eq!(events.len(), 1);
9837 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9838 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9839 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9841 _ => panic!("Unexpected event"),
9844 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9847 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9848 *feerate_lock = 1000;
9850 nodes[0].node.timer_tick_occurred();
9851 check_added_monitors!(nodes[0], 1);
9853 let events = nodes[0].node.get_and_clear_pending_msg_events();
9854 assert_eq!(events.len(), 1);
9856 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9857 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9858 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9859 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9860 check_closed_broadcast!(nodes[1], true);
9861 check_added_monitors!(nodes[1], 1);
9863 _ => panic!("Unexpected event"),
9867 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9868 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9869 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9870 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9871 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9872 let min_final_cltv_expiry_delta = 120;
9873 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9874 min_final_cltv_expiry_delta - 2 };
9875 let recv_value = 100_000;
9877 create_chan_between_nodes(&nodes[0], &nodes[1]);
9879 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9880 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9881 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9882 Some(recv_value), Some(min_final_cltv_expiry_delta));
9883 (payment_hash, payment_preimage, payment_secret)
9885 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9886 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9888 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9889 nodes[0].node.send_payment_with_route(&route, payment_hash,
9890 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9891 check_added_monitors!(nodes[0], 1);
9892 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9893 assert_eq!(events.len(), 1);
9894 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9895 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9896 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9897 expect_pending_htlcs_forwardable!(nodes[1]);
9900 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9901 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9903 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9905 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9907 check_added_monitors!(nodes[1], 1);
9909 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9910 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9911 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9913 expect_payment_failed!(nodes[0], payment_hash, true);
9918 fn test_payment_with_custom_min_cltv_expiry_delta() {
9919 do_payment_with_custom_min_final_cltv_expiry(false, false);
9920 do_payment_with_custom_min_final_cltv_expiry(false, true);
9921 do_payment_with_custom_min_final_cltv_expiry(true, false);
9922 do_payment_with_custom_min_final_cltv_expiry(true, true);
9926 fn test_disconnects_peer_awaiting_response_ticks() {
9927 // Tests that nodes which are awaiting on a response critical for channel responsiveness
9928 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9929 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9930 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9931 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9932 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9934 // Asserts a disconnect event is queued to the user.
9935 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9936 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9937 if let MessageSendEvent::HandleError { action, .. } = event {
9938 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9947 assert_eq!(disconnect_event.is_some(), should_disconnect);
9950 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9951 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9952 let check_disconnect = |node: &Node| {
9953 // No disconnect without any timer ticks.
9954 check_disconnect_event(node, false);
9956 // No disconnect with 1 timer tick less than required.
9957 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9958 node.node.timer_tick_occurred();
9959 check_disconnect_event(node, false);
9962 // Disconnect after reaching the required ticks.
9963 node.node.timer_tick_occurred();
9964 check_disconnect_event(node, true);
9966 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9967 node.node.timer_tick_occurred();
9968 check_disconnect_event(node, true);
9971 create_chan_between_nodes(&nodes[0], &nodes[1]);
9973 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9974 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9975 nodes[0].node.timer_tick_occurred();
9976 check_added_monitors!(&nodes[0], 1);
9977 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9978 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9979 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9980 check_added_monitors!(&nodes[1], 1);
9982 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
9983 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
9984 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
9985 check_added_monitors!(&nodes[0], 1);
9986 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
9987 check_added_monitors(&nodes[0], 1);
9989 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
9990 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
9991 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9992 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9993 check_disconnect(&nodes[1]);
9995 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
9997 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
9998 // final `RevokeAndACK` to Bob to complete it.
9999 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10000 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10001 let bob_init = msgs::Init {
10002 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10004 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10005 let alice_init = msgs::Init {
10006 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10008 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10010 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10011 // received Bob's yet, so she should disconnect him after reaching
10012 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10013 let alice_channel_reestablish = get_event_msg!(
10014 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10016 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10017 check_disconnect(&nodes[0]);
10019 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10020 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10021 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10022 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10028 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10030 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10031 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10032 nodes[0].node.timer_tick_occurred();
10033 check_disconnect_event(&nodes[0], false);
10036 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10037 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10038 check_disconnect(&nodes[1]);
10040 // Finally, have Bob process the last message.
10041 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10042 check_added_monitors(&nodes[1], 1);
10044 // At this point, neither node should attempt to disconnect each other, since they aren't
10045 // waiting on any messages.
10046 for node in &nodes {
10047 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10048 node.node.timer_tick_occurred();
10049 check_disconnect_event(node, false);