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::chain::keysinterface::{BaseSign, EntropySource, KeysInterface};
21 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 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};
23 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
24 use crate::ln::channel::{Channel, ChannelError};
25 use crate::ln::{chan_utils, onion_utils};
26 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
28 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use crate::ln::features::{ChannelFeatures, NodeFeatures};
31 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use crate::util::enforcing_trait_impls::EnforcingSigner;
33 use crate::util::test_utils;
34 use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::config::UserConfig;
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
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, TxMerkleNode, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &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".to_string(), 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].features = channelmanager::provided_init_features().clear_wumbo();
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &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(), channelmanager::provided_init_features(), &accept_channel_message);
179 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
180 chan.holder_selected_channel_reserve_satoshis = 0;
181 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
184 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
185 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
186 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
188 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
189 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
190 if send_from_initiator {
191 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
192 // Note that for outbound channels we have to consider the commitment tx fee and the
193 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
194 // well as an additional HTLC.
195 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
197 send_payment(&nodes[1], &[&nodes[0]], push_amt);
202 fn test_counterparty_no_reserve() {
203 do_test_counterparty_no_reserve(true);
204 do_test_counterparty_no_reserve(false);
208 fn test_async_inbound_update_fee() {
209 let chanmon_cfgs = create_chanmon_cfgs(2);
210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
212 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
213 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
216 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
220 // send (1) commitment_signed -.
221 // <- update_add_htlc/commitment_signed
222 // send (2) RAA (awaiting remote revoke) -.
223 // (1) commitment_signed is delivered ->
224 // .- send (3) RAA (awaiting remote revoke)
225 // (2) RAA is delivered ->
226 // .- send (4) commitment_signed
227 // <- (3) RAA is delivered
228 // send (5) commitment_signed -.
229 // <- (4) commitment_signed is delivered
231 // (5) commitment_signed is delivered ->
233 // (6) RAA is delivered ->
235 // First nodes[0] generates an update_fee
237 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
240 nodes[0].node.timer_tick_occurred();
241 check_added_monitors!(nodes[0], 1);
243 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
244 assert_eq!(events_0.len(), 1);
245 let (update_msg, commitment_signed) = match events_0[0] { // (1)
246 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
247 (update_fee.as_ref(), commitment_signed)
249 _ => panic!("Unexpected event"),
252 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
254 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
255 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
256 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
257 check_added_monitors!(nodes[1], 1);
259 let payment_event = {
260 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
261 assert_eq!(events_1.len(), 1);
262 SendEvent::from_event(events_1.remove(0))
264 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
265 assert_eq!(payment_event.msgs.len(), 1);
267 // ...now when the messages get delivered everyone should be happy
268 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
269 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
270 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
272 check_added_monitors!(nodes[0], 1);
274 // deliver(1), generate (3):
275 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
276 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
277 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
278 check_added_monitors!(nodes[1], 1);
280 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
281 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
282 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
283 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
284 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
285 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
286 assert!(bs_update.update_fee.is_none()); // (4)
287 check_added_monitors!(nodes[1], 1);
289 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
290 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
291 assert!(as_update.update_add_htlcs.is_empty()); // (5)
292 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
293 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
294 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
295 assert!(as_update.update_fee.is_none()); // (5)
296 check_added_monitors!(nodes[0], 1);
298 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
299 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
300 // only (6) so get_event_msg's assert(len == 1) passes
301 check_added_monitors!(nodes[0], 1);
303 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
304 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
305 check_added_monitors!(nodes[1], 1);
307 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
308 check_added_monitors!(nodes[0], 1);
310 let events_2 = nodes[0].node.get_and_clear_pending_events();
311 assert_eq!(events_2.len(), 1);
313 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
314 _ => panic!("Unexpected event"),
317 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
318 check_added_monitors!(nodes[1], 1);
322 fn test_update_fee_unordered_raa() {
323 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
324 // crash in an earlier version of the update_fee patch)
325 let chanmon_cfgs = create_chanmon_cfgs(2);
326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
328 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
329 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
332 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
334 // First nodes[0] generates an update_fee
336 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
339 nodes[0].node.timer_tick_occurred();
340 check_added_monitors!(nodes[0], 1);
342 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
343 assert_eq!(events_0.len(), 1);
344 let update_msg = match events_0[0] { // (1)
345 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
348 _ => panic!("Unexpected event"),
351 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
353 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
354 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
355 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
356 check_added_monitors!(nodes[1], 1);
358 let payment_event = {
359 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
360 assert_eq!(events_1.len(), 1);
361 SendEvent::from_event(events_1.remove(0))
363 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
364 assert_eq!(payment_event.msgs.len(), 1);
366 // ...now when the messages get delivered everyone should be happy
367 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
368 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
369 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
371 check_added_monitors!(nodes[0], 1);
373 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
374 check_added_monitors!(nodes[1], 1);
376 // We can't continue, sadly, because our (1) now has a bogus signature
380 fn test_multi_flight_update_fee() {
381 let chanmon_cfgs = create_chanmon_cfgs(2);
382 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
383 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
384 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
385 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
388 // update_fee/commitment_signed ->
389 // .- send (1) RAA and (2) commitment_signed
390 // update_fee (never committed) ->
392 // We have to manually generate the above update_fee, it is allowed by the protocol but we
393 // don't track which updates correspond to which revoke_and_ack responses so we're in
394 // AwaitingRAA mode and will not generate the update_fee yet.
395 // <- (1) RAA delivered
396 // (3) is generated and send (4) CS -.
397 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
398 // know the per_commitment_point to use for it.
399 // <- (2) commitment_signed delivered
401 // B should send no response here
402 // (4) commitment_signed delivered ->
403 // <- RAA/commitment_signed delivered
406 // First nodes[0] generates an update_fee
409 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
410 initial_feerate = *feerate_lock;
411 *feerate_lock = initial_feerate + 20;
413 nodes[0].node.timer_tick_occurred();
414 check_added_monitors!(nodes[0], 1);
416 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
417 assert_eq!(events_0.len(), 1);
418 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
419 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
420 (update_fee.as_ref().unwrap(), commitment_signed)
422 _ => panic!("Unexpected event"),
425 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
426 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
427 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
428 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
429 check_added_monitors!(nodes[1], 1);
431 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
434 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
435 *feerate_lock = initial_feerate + 40;
437 nodes[0].node.timer_tick_occurred();
438 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
439 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
441 // Create the (3) update_fee message that nodes[0] will generate before it does...
442 let mut update_msg_2 = msgs::UpdateFee {
443 channel_id: update_msg_1.channel_id.clone(),
444 feerate_per_kw: (initial_feerate + 30) as u32,
447 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
449 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
451 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
453 // Deliver (1), generating (3) and (4)
454 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
455 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
456 check_added_monitors!(nodes[0], 1);
457 assert!(as_second_update.update_add_htlcs.is_empty());
458 assert!(as_second_update.update_fulfill_htlcs.is_empty());
459 assert!(as_second_update.update_fail_htlcs.is_empty());
460 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
461 // Check that the update_fee newly generated matches what we delivered:
462 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
463 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
465 // Deliver (2) commitment_signed
466 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
467 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
468 check_added_monitors!(nodes[0], 1);
469 // No commitment_signed so get_event_msg's assert(len == 1) passes
471 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
472 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
473 check_added_monitors!(nodes[1], 1);
476 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
477 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
478 check_added_monitors!(nodes[1], 1);
480 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
481 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
482 check_added_monitors!(nodes[0], 1);
484 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
485 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
486 // No commitment_signed so get_event_msg's assert(len == 1) passes
487 check_added_monitors!(nodes[0], 1);
489 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
490 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
491 check_added_monitors!(nodes[1], 1);
494 fn do_test_sanity_on_in_flight_opens(steps: u8) {
495 // Previously, we had issues deserializing channels when we hadn't connected the first block
496 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
497 // serialization round-trips and simply do steps towards opening a channel and then drop the
500 let chanmon_cfgs = create_chanmon_cfgs(2);
501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
503 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
505 if steps & 0b1000_0000 != 0{
507 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
510 connect_block(&nodes[0], &block);
511 connect_block(&nodes[1], &block);
514 if steps & 0x0f == 0 { return; }
515 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
516 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
518 if steps & 0x0f == 1 { return; }
519 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
520 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
522 if steps & 0x0f == 2 { return; }
523 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
525 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
527 if steps & 0x0f == 3 { return; }
528 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
529 check_added_monitors!(nodes[0], 0);
530 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
532 if steps & 0x0f == 4 { return; }
533 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
535 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
536 assert_eq!(added_monitors.len(), 1);
537 assert_eq!(added_monitors[0].0, funding_output);
538 added_monitors.clear();
540 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
542 if steps & 0x0f == 5 { return; }
543 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
545 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
546 assert_eq!(added_monitors.len(), 1);
547 assert_eq!(added_monitors[0].0, funding_output);
548 added_monitors.clear();
551 let events_4 = nodes[0].node.get_and_clear_pending_events();
552 assert_eq!(events_4.len(), 0);
554 if steps & 0x0f == 6 { return; }
555 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
557 if steps & 0x0f == 7 { return; }
558 confirm_transaction_at(&nodes[0], &tx, 2);
559 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
560 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
561 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
565 fn test_sanity_on_in_flight_opens() {
566 do_test_sanity_on_in_flight_opens(0);
567 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
568 do_test_sanity_on_in_flight_opens(1);
569 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
570 do_test_sanity_on_in_flight_opens(2);
571 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
572 do_test_sanity_on_in_flight_opens(3);
573 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
574 do_test_sanity_on_in_flight_opens(4);
575 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
576 do_test_sanity_on_in_flight_opens(5);
577 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
578 do_test_sanity_on_in_flight_opens(6);
579 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
580 do_test_sanity_on_in_flight_opens(7);
581 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
582 do_test_sanity_on_in_flight_opens(8);
583 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
587 fn test_update_fee_vanilla() {
588 let chanmon_cfgs = create_chanmon_cfgs(2);
589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
591 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
592 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
595 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
598 nodes[0].node.timer_tick_occurred();
599 check_added_monitors!(nodes[0], 1);
601 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
602 assert_eq!(events_0.len(), 1);
603 let (update_msg, commitment_signed) = match events_0[0] {
604 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 } } => {
605 (update_fee.as_ref(), commitment_signed)
607 _ => panic!("Unexpected event"),
609 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
611 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
612 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
613 check_added_monitors!(nodes[1], 1);
615 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
616 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
617 check_added_monitors!(nodes[0], 1);
619 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
620 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
621 // No commitment_signed so get_event_msg's assert(len == 1) passes
622 check_added_monitors!(nodes[0], 1);
624 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
625 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
626 check_added_monitors!(nodes[1], 1);
630 fn test_update_fee_that_funder_cannot_afford() {
631 let chanmon_cfgs = create_chanmon_cfgs(2);
632 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
633 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
634 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
635 let channel_value = 5000;
637 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
638 let channel_id = chan.2;
639 let secp_ctx = Secp256k1::new();
640 let default_config = UserConfig::default();
641 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
643 let opt_anchors = false;
645 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
646 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
647 // calculate two different feerates here - the expected local limit as well as the expected
649 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;
650 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
652 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
653 *feerate_lock = feerate;
655 nodes[0].node.timer_tick_occurred();
656 check_added_monitors!(nodes[0], 1);
657 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
659 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
661 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
663 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
665 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
667 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
668 assert_eq!(commitment_tx.output.len(), 2);
669 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
670 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
671 actual_fee = channel_value - actual_fee;
672 assert_eq!(total_fee, actual_fee);
676 // Increment the feerate by a small constant, accounting for rounding errors
677 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
680 nodes[0].node.timer_tick_occurred();
681 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
682 check_added_monitors!(nodes[0], 0);
684 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
686 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
687 // needed to sign the new commitment tx and (2) sign the new commitment tx.
688 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
689 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
690 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
691 let chan_signer = local_chan.get_signer();
692 let pubkeys = chan_signer.pubkeys();
693 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
694 pubkeys.funding_pubkey)
696 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
697 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
698 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
699 let chan_signer = remote_chan.get_signer();
700 let pubkeys = chan_signer.pubkeys();
701 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
702 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
703 pubkeys.funding_pubkey)
706 // Assemble the set of keys we can use for signatures for our commitment_signed message.
707 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
708 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
711 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
712 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
713 let local_chan_signer = local_chan.get_signer();
714 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
715 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
716 INITIAL_COMMITMENT_NUMBER - 1,
718 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
719 opt_anchors, local_funding, remote_funding,
720 commit_tx_keys.clone(),
721 non_buffer_feerate + 4,
723 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
725 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
728 let commit_signed_msg = msgs::CommitmentSigned {
731 htlc_signatures: res.1
734 let update_fee = msgs::UpdateFee {
736 feerate_per_kw: non_buffer_feerate + 4,
739 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
741 //While producing the commitment_signed response after handling a received update_fee request the
742 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
743 //Should produce and error.
744 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
745 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
746 check_added_monitors!(nodes[1], 1);
747 check_closed_broadcast!(nodes[1], true);
748 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
752 fn test_update_fee_with_fundee_update_add_htlc() {
753 let chanmon_cfgs = create_chanmon_cfgs(2);
754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
756 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
757 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
760 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
763 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
766 nodes[0].node.timer_tick_occurred();
767 check_added_monitors!(nodes[0], 1);
769 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
770 assert_eq!(events_0.len(), 1);
771 let (update_msg, commitment_signed) = match events_0[0] {
772 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 } } => {
773 (update_fee.as_ref(), commitment_signed)
775 _ => panic!("Unexpected event"),
777 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
778 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
779 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
780 check_added_monitors!(nodes[1], 1);
782 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
784 // nothing happens since node[1] is in AwaitingRemoteRevoke
785 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
787 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
788 assert_eq!(added_monitors.len(), 0);
789 added_monitors.clear();
791 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
792 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
793 // node[1] has nothing to do
795 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797 check_added_monitors!(nodes[0], 1);
799 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
800 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
801 // No commitment_signed so get_event_msg's assert(len == 1) passes
802 check_added_monitors!(nodes[0], 1);
803 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
804 check_added_monitors!(nodes[1], 1);
805 // AwaitingRemoteRevoke ends here
807 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
808 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
809 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
810 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
811 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
812 assert_eq!(commitment_update.update_fee.is_none(), true);
814 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
815 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
816 check_added_monitors!(nodes[0], 1);
817 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
819 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
820 check_added_monitors!(nodes[1], 1);
821 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
823 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
824 check_added_monitors!(nodes[1], 1);
825 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
826 // No commitment_signed so get_event_msg's assert(len == 1) passes
828 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
829 check_added_monitors!(nodes[0], 1);
830 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
832 expect_pending_htlcs_forwardable!(nodes[0]);
834 let events = nodes[0].node.get_and_clear_pending_events();
835 assert_eq!(events.len(), 1);
837 Event::PaymentClaimable { .. } => { },
838 _ => panic!("Unexpected event"),
841 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
843 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
844 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
845 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
846 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
847 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
851 fn test_update_fee() {
852 let chanmon_cfgs = create_chanmon_cfgs(2);
853 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
854 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
855 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
856 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
857 let channel_id = chan.2;
860 // (1) update_fee/commitment_signed ->
861 // <- (2) revoke_and_ack
862 // .- send (3) commitment_signed
863 // (4) update_fee/commitment_signed ->
864 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
865 // <- (3) commitment_signed delivered
866 // send (6) revoke_and_ack -.
867 // <- (5) deliver revoke_and_ack
868 // (6) deliver revoke_and_ack ->
869 // .- send (7) commitment_signed in response to (4)
870 // <- (7) deliver commitment_signed
873 // Create and deliver (1)...
876 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
877 feerate = *feerate_lock;
878 *feerate_lock = feerate + 20;
880 nodes[0].node.timer_tick_occurred();
881 check_added_monitors!(nodes[0], 1);
883 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
884 assert_eq!(events_0.len(), 1);
885 let (update_msg, commitment_signed) = match events_0[0] {
886 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 } } => {
887 (update_fee.as_ref(), commitment_signed)
889 _ => panic!("Unexpected event"),
891 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
893 // Generate (2) and (3):
894 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
895 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
896 check_added_monitors!(nodes[1], 1);
899 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
900 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
901 check_added_monitors!(nodes[0], 1);
903 // Create and deliver (4)...
905 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
906 *feerate_lock = feerate + 30;
908 nodes[0].node.timer_tick_occurred();
909 check_added_monitors!(nodes[0], 1);
910 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
911 assert_eq!(events_0.len(), 1);
912 let (update_msg, commitment_signed) = match events_0[0] {
913 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 } } => {
914 (update_fee.as_ref(), commitment_signed)
916 _ => panic!("Unexpected event"),
919 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
920 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
921 check_added_monitors!(nodes[1], 1);
923 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
924 // No commitment_signed so get_event_msg's assert(len == 1) passes
926 // Handle (3), creating (6):
927 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
928 check_added_monitors!(nodes[0], 1);
929 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
930 // No commitment_signed so get_event_msg's assert(len == 1) passes
933 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
934 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
935 check_added_monitors!(nodes[0], 1);
937 // Deliver (6), creating (7):
938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
939 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
940 assert!(commitment_update.update_add_htlcs.is_empty());
941 assert!(commitment_update.update_fulfill_htlcs.is_empty());
942 assert!(commitment_update.update_fail_htlcs.is_empty());
943 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
944 assert!(commitment_update.update_fee.is_none());
945 check_added_monitors!(nodes[1], 1);
948 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
949 check_added_monitors!(nodes[0], 1);
950 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
951 // No commitment_signed so get_event_msg's assert(len == 1) passes
953 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
954 check_added_monitors!(nodes[1], 1);
955 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
957 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
958 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
959 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
960 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
961 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
965 fn fake_network_test() {
966 // Simple test which builds a network of ChannelManagers, connects them to each other, and
967 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
968 let chanmon_cfgs = create_chanmon_cfgs(4);
969 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
970 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
971 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
973 // Create some initial channels
974 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
975 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
976 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
978 // Rebalance the network a bit by relaying one payment through all the channels...
979 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
980 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
981 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
982 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
984 // Send some more payments
985 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
986 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
987 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
989 // Test failure packets
990 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
991 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
993 // Add a new channel that skips 3
994 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
996 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
997 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
998 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
999 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1000 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1001 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1002 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1004 // Do some rebalance loop payments, simultaneously
1005 let mut hops = Vec::with_capacity(3);
1006 hops.push(RouteHop {
1007 pubkey: nodes[2].node.get_our_node_id(),
1008 node_features: NodeFeatures::empty(),
1009 short_channel_id: chan_2.0.contents.short_channel_id,
1010 channel_features: ChannelFeatures::empty(),
1012 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1014 hops.push(RouteHop {
1015 pubkey: nodes[3].node.get_our_node_id(),
1016 node_features: NodeFeatures::empty(),
1017 short_channel_id: chan_3.0.contents.short_channel_id,
1018 channel_features: ChannelFeatures::empty(),
1020 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1022 hops.push(RouteHop {
1023 pubkey: nodes[1].node.get_our_node_id(),
1024 node_features: channelmanager::provided_node_features(),
1025 short_channel_id: chan_4.0.contents.short_channel_id,
1026 channel_features: channelmanager::provided_channel_features(),
1028 cltv_expiry_delta: TEST_FINAL_CLTV,
1030 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;
1031 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;
1032 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1034 let mut hops = Vec::with_capacity(3);
1035 hops.push(RouteHop {
1036 pubkey: nodes[3].node.get_our_node_id(),
1037 node_features: NodeFeatures::empty(),
1038 short_channel_id: chan_4.0.contents.short_channel_id,
1039 channel_features: ChannelFeatures::empty(),
1041 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1043 hops.push(RouteHop {
1044 pubkey: nodes[2].node.get_our_node_id(),
1045 node_features: NodeFeatures::empty(),
1046 short_channel_id: chan_3.0.contents.short_channel_id,
1047 channel_features: ChannelFeatures::empty(),
1049 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1051 hops.push(RouteHop {
1052 pubkey: nodes[1].node.get_our_node_id(),
1053 node_features: channelmanager::provided_node_features(),
1054 short_channel_id: chan_2.0.contents.short_channel_id,
1055 channel_features: channelmanager::provided_channel_features(),
1057 cltv_expiry_delta: TEST_FINAL_CLTV,
1059 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;
1060 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;
1061 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1063 // Claim the rebalances...
1064 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1065 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1067 // Close down the channels...
1068 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1069 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1070 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1072 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1073 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1074 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1075 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1076 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1077 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1078 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1079 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1083 fn holding_cell_htlc_counting() {
1084 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1085 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1086 // commitment dance rounds.
1087 let chanmon_cfgs = create_chanmon_cfgs(3);
1088 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1089 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1090 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1091 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1092 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1094 let mut payments = Vec::new();
1095 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1096 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1097 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1098 payments.push((payment_preimage, payment_hash));
1100 check_added_monitors!(nodes[1], 1);
1102 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1103 assert_eq!(events.len(), 1);
1104 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1105 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1107 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1108 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1110 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1112 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)), true, APIError::ChannelUnavailable { ref err },
1113 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1114 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1115 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1118 // This should also be true if we try to forward a payment.
1119 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1121 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1122 check_added_monitors!(nodes[0], 1);
1125 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1126 assert_eq!(events.len(), 1);
1127 let payment_event = SendEvent::from_event(events.pop().unwrap());
1128 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1130 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1131 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1132 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1133 // fails), the second will process the resulting failure and fail the HTLC backward.
1134 expect_pending_htlcs_forwardable!(nodes[1]);
1135 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 }]);
1136 check_added_monitors!(nodes[1], 1);
1138 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1139 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1140 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1142 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1144 // Now forward all the pending HTLCs and claim them back
1145 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1146 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1147 check_added_monitors!(nodes[2], 1);
1149 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1150 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1151 check_added_monitors!(nodes[1], 1);
1152 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1154 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1155 check_added_monitors!(nodes[1], 1);
1156 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1158 for ref update in as_updates.update_add_htlcs.iter() {
1159 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1162 check_added_monitors!(nodes[2], 1);
1163 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1164 check_added_monitors!(nodes[2], 1);
1165 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168 check_added_monitors!(nodes[1], 1);
1169 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_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1173 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1174 check_added_monitors!(nodes[2], 1);
1176 expect_pending_htlcs_forwardable!(nodes[2]);
1178 let events = nodes[2].node.get_and_clear_pending_events();
1179 assert_eq!(events.len(), payments.len());
1180 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1182 &Event::PaymentClaimable { ref payment_hash, .. } => {
1183 assert_eq!(*payment_hash, *hash);
1185 _ => panic!("Unexpected event"),
1189 for (preimage, _) in payments.drain(..) {
1190 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1193 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1197 fn duplicate_htlc_test() {
1198 // Test that we accept duplicate payment_hash HTLCs across the network and that
1199 // claiming/failing them are all separate and don't affect each other
1200 let chanmon_cfgs = create_chanmon_cfgs(6);
1201 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1202 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1203 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1205 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1206 create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1207 create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1208 create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1209 create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1210 create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1212 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1214 *nodes[0].network_payment_count.borrow_mut() -= 1;
1215 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1217 *nodes[0].network_payment_count.borrow_mut() -= 1;
1218 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1220 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1221 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1222 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1226 fn test_duplicate_htlc_different_direction_onchain() {
1227 // Test that ChannelMonitor doesn't generate 2 preimage txn
1228 // when we have 2 HTLCs with same preimage that go across a node
1229 // in opposite directions, even with the same payment secret.
1230 let chanmon_cfgs = create_chanmon_cfgs(2);
1231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1233 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1235 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1238 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1240 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1242 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1243 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1244 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1246 // Provide preimage to node 0 by claiming payment
1247 nodes[0].node.claim_funds(payment_preimage);
1248 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1249 check_added_monitors!(nodes[0], 1);
1251 // Broadcast node 1 commitment txn
1252 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1254 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1255 let mut has_both_htlcs = 0; // check htlcs match ones committed
1256 for outp in remote_txn[0].output.iter() {
1257 if outp.value == 800_000 / 1000 {
1258 has_both_htlcs += 1;
1259 } else if outp.value == 900_000 / 1000 {
1260 has_both_htlcs += 1;
1263 assert_eq!(has_both_htlcs, 2);
1265 mine_transaction(&nodes[0], &remote_txn[0]);
1266 check_added_monitors!(nodes[0], 1);
1267 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1268 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1270 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1271 assert_eq!(claim_txn.len(), 3);
1273 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1274 check_spends!(claim_txn[1], remote_txn[0]);
1275 check_spends!(claim_txn[2], remote_txn[0]);
1276 let preimage_tx = &claim_txn[0];
1277 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1278 (&claim_txn[1], &claim_txn[2])
1280 (&claim_txn[2], &claim_txn[1])
1283 assert_eq!(preimage_tx.input.len(), 1);
1284 assert_eq!(preimage_bump_tx.input.len(), 1);
1286 assert_eq!(preimage_tx.input.len(), 1);
1287 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1288 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1290 assert_eq!(timeout_tx.input.len(), 1);
1291 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1292 check_spends!(timeout_tx, remote_txn[0]);
1293 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1295 let events = nodes[0].node.get_and_clear_pending_msg_events();
1296 assert_eq!(events.len(), 3);
1299 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1300 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1301 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1302 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1304 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, .. } } => {
1305 assert!(update_add_htlcs.is_empty());
1306 assert!(update_fail_htlcs.is_empty());
1307 assert_eq!(update_fulfill_htlcs.len(), 1);
1308 assert!(update_fail_malformed_htlcs.is_empty());
1309 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1311 _ => panic!("Unexpected event"),
1317 fn test_basic_channel_reserve() {
1318 let chanmon_cfgs = create_chanmon_cfgs(2);
1319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1322 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1324 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1325 let channel_reserve = chan_stat.channel_reserve_msat;
1327 // The 2* and +1 are for the fee spike reserve.
1328 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1329 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1330 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1331 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1333 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1335 &APIError::ChannelUnavailable{ref err} =>
1336 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1337 _ => panic!("Unexpected error variant"),
1340 _ => panic!("Unexpected error variant"),
1342 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1343 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1345 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1349 fn test_fee_spike_violation_fails_htlc() {
1350 let chanmon_cfgs = create_chanmon_cfgs(2);
1351 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1352 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1353 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1354 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1356 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1357 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1358 let secp_ctx = Secp256k1::new();
1359 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1361 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1363 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1364 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1365 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1366 let msg = msgs::UpdateAddHTLC {
1369 amount_msat: htlc_msat,
1370 payment_hash: payment_hash,
1371 cltv_expiry: htlc_cltv,
1372 onion_routing_packet: onion_packet,
1375 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1377 // Now manually create the commitment_signed message corresponding to the update_add
1378 // nodes[0] just sent. In the code for construction of this message, "local" refers
1379 // to the sender of the message, and "remote" refers to the receiver.
1381 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1383 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1385 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1386 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1387 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1388 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1389 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1390 let chan_signer = local_chan.get_signer();
1391 // Make the signer believe we validated another commitment, so we can release the secret
1392 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1394 let pubkeys = chan_signer.pubkeys();
1395 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1396 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1397 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1398 chan_signer.pubkeys().funding_pubkey)
1400 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1401 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1402 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1403 let chan_signer = remote_chan.get_signer();
1404 let pubkeys = chan_signer.pubkeys();
1405 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1406 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1407 chan_signer.pubkeys().funding_pubkey)
1410 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1411 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1412 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1414 // Build the remote commitment transaction so we can sign it, and then later use the
1415 // signature for the commitment_signed message.
1416 let local_chan_balance = 1313;
1418 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1420 amount_msat: 3460001,
1421 cltv_expiry: htlc_cltv,
1423 transaction_output_index: Some(1),
1426 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1429 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1430 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1431 let local_chan_signer = local_chan.get_signer();
1432 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1436 local_chan.opt_anchors(), local_funding, remote_funding,
1437 commit_tx_keys.clone(),
1439 &mut vec![(accepted_htlc_info, ())],
1440 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1442 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1445 let commit_signed_msg = msgs::CommitmentSigned {
1448 htlc_signatures: res.1
1451 // Send the commitment_signed message to the nodes[1].
1452 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1453 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1455 // Send the RAA to nodes[1].
1456 let raa_msg = msgs::RevokeAndACK {
1458 per_commitment_secret: local_secret,
1459 next_per_commitment_point: next_local_point
1461 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1463 let events = nodes[1].node.get_and_clear_pending_msg_events();
1464 assert_eq!(events.len(), 1);
1465 // Make sure the HTLC failed in the way we expect.
1467 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1468 assert_eq!(update_fail_htlcs.len(), 1);
1469 update_fail_htlcs[0].clone()
1471 _ => panic!("Unexpected event"),
1473 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1474 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1476 check_added_monitors!(nodes[1], 2);
1480 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1481 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1482 // Set the fee rate for the channel very high, to the point where the fundee
1483 // sending any above-dust amount would result in a channel reserve violation.
1484 // In this test we check that we would be prevented from sending an HTLC in
1486 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1487 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1488 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1489 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1490 let default_config = UserConfig::default();
1491 let opt_anchors = false;
1493 let mut push_amt = 100_000_000;
1494 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1496 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1498 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1500 // Sending exactly enough to hit the reserve amount should be accepted
1501 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1502 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1505 // However one more HTLC should be significantly over the reserve amount and fail.
1506 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1507 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1508 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1509 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1510 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1514 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1515 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1516 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1519 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1520 let default_config = UserConfig::default();
1521 let opt_anchors = false;
1523 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1524 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1525 // transaction fee with 0 HTLCs (183 sats)).
1526 let mut push_amt = 100_000_000;
1527 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1528 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1529 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1531 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1532 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1533 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1536 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1537 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1538 let secp_ctx = Secp256k1::new();
1539 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1540 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1541 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1542 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1543 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1544 let msg = msgs::UpdateAddHTLC {
1546 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1547 amount_msat: htlc_msat,
1548 payment_hash: payment_hash,
1549 cltv_expiry: htlc_cltv,
1550 onion_routing_packet: onion_packet,
1553 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1554 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1555 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);
1556 assert_eq!(nodes[0].node.list_channels().len(), 0);
1557 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1558 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1559 check_added_monitors!(nodes[0], 1);
1560 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() });
1564 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1565 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1566 // calculating our commitment transaction fee (this was previously broken).
1567 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1568 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1572 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1573 let default_config = UserConfig::default();
1574 let opt_anchors = false;
1576 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1577 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1578 // transaction fee with 0 HTLCs (183 sats)).
1579 let mut push_amt = 100_000_000;
1580 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1581 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1582 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1584 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1585 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1586 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1587 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1588 // commitment transaction fee.
1589 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1591 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1592 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1593 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1596 // One more than the dust amt should fail, however.
1597 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1598 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1599 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1603 fn test_chan_init_feerate_unaffordability() {
1604 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1605 // channel reserve and feerate requirements.
1606 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1607 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1608 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1609 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1610 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1611 let default_config = UserConfig::default();
1612 let opt_anchors = false;
1614 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1616 let mut push_amt = 100_000_000;
1617 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1618 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1619 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1621 // During open, we don't have a "counterparty channel reserve" to check against, so that
1622 // requirement only comes into play on the open_channel handling side.
1623 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1624 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1625 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1626 open_channel_msg.push_msat += 1;
1627 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1629 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1630 assert_eq!(msg_events.len(), 1);
1631 match msg_events[0] {
1632 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1633 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1635 _ => panic!("Unexpected event"),
1640 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1641 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1642 // calculating our counterparty's commitment transaction fee (this was previously broken).
1643 let chanmon_cfgs = create_chanmon_cfgs(2);
1644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1646 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1647 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1649 let payment_amt = 46000; // Dust amount
1650 // In the previous code, these first four payments would succeed.
1651 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1652 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1653 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1654 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1656 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1657 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1658 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1659 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1660 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1664 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1665 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1666 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1671 let chanmon_cfgs = create_chanmon_cfgs(3);
1672 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1673 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1674 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1675 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1676 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1679 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1680 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1681 let feerate = get_feerate!(nodes[0], chan.2);
1682 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1684 // Add a 2* and +1 for the fee spike reserve.
1685 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1686 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;
1687 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1689 // Add a pending HTLC.
1690 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1691 let payment_event_1 = {
1692 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1693 check_added_monitors!(nodes[0], 1);
1695 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1696 assert_eq!(events.len(), 1);
1697 SendEvent::from_event(events.remove(0))
1699 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1701 // Attempt to trigger a channel reserve violation --> payment failure.
1702 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1703 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;
1704 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1705 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1707 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1708 let secp_ctx = Secp256k1::new();
1709 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1710 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1711 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1712 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1713 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1714 let msg = msgs::UpdateAddHTLC {
1717 amount_msat: htlc_msat + 1,
1718 payment_hash: our_payment_hash_1,
1719 cltv_expiry: htlc_cltv,
1720 onion_routing_packet: onion_packet,
1723 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1724 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1725 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1726 assert_eq!(nodes[1].node.list_channels().len(), 1);
1727 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1728 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1729 check_added_monitors!(nodes[1], 1);
1730 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1734 fn test_inbound_outbound_capacity_is_not_zero() {
1735 let chanmon_cfgs = create_chanmon_cfgs(2);
1736 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1737 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1738 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1739 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1740 let channels0 = node_chanmgrs[0].list_channels();
1741 let channels1 = node_chanmgrs[1].list_channels();
1742 let default_config = UserConfig::default();
1743 assert_eq!(channels0.len(), 1);
1744 assert_eq!(channels1.len(), 1);
1746 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1747 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1748 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1750 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1751 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1754 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1755 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1759 fn test_channel_reserve_holding_cell_htlcs() {
1760 let chanmon_cfgs = create_chanmon_cfgs(3);
1761 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1762 // When this test was written, the default base fee floated based on the HTLC count.
1763 // It is now fixed, so we simply set the fee to the expected value here.
1764 let mut config = test_default_channel_config();
1765 config.channel_config.forwarding_fee_base_msat = 239;
1766 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1767 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1768 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1769 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1771 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1772 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1774 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1775 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1777 macro_rules! expect_forward {
1779 let mut events = $node.node.get_and_clear_pending_msg_events();
1780 assert_eq!(events.len(), 1);
1781 check_added_monitors!($node, 1);
1782 let payment_event = SendEvent::from_event(events.remove(0));
1787 let feemsat = 239; // set above
1788 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1789 let feerate = get_feerate!(nodes[0], chan_1.2);
1790 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1792 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1794 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1796 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1797 .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1798 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1799 route.paths[0].last_mut().unwrap().fee_msat += 1;
1800 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1802 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1803 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1804 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1805 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1808 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1809 // nodes[0]'s wealth
1811 let amt_msat = recv_value_0 + total_fee_msat;
1812 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1813 // Also, ensure that each payment has enough to be over the dust limit to
1814 // ensure it'll be included in each commit tx fee calculation.
1815 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1816 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1817 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1821 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1822 .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1823 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1824 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1825 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1827 let (stat01_, stat11_, stat12_, stat22_) = (
1828 get_channel_value_stat!(nodes[0], chan_1.2),
1829 get_channel_value_stat!(nodes[1], chan_1.2),
1830 get_channel_value_stat!(nodes[1], chan_2.2),
1831 get_channel_value_stat!(nodes[2], chan_2.2),
1834 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1835 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1836 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1837 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1838 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1841 // adding pending output.
1842 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1843 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1844 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1845 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1846 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1847 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1848 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1849 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1850 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1852 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1853 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1854 let amt_msat_1 = recv_value_1 + total_fee_msat;
1856 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);
1857 let payment_event_1 = {
1858 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1859 check_added_monitors!(nodes[0], 1);
1861 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1862 assert_eq!(events.len(), 1);
1863 SendEvent::from_event(events.remove(0))
1865 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1867 // channel reserve test with htlc pending output > 0
1868 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1870 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1871 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1872 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1873 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1876 // split the rest to test holding cell
1877 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1878 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1879 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1880 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1882 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1883 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);
1886 // now see if they go through on both sides
1887 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);
1888 // but this will stuck in the holding cell
1889 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1890 check_added_monitors!(nodes[0], 0);
1891 let events = nodes[0].node.get_and_clear_pending_events();
1892 assert_eq!(events.len(), 0);
1894 // test with outbound holding cell amount > 0
1896 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1897 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1898 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1899 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1900 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
1903 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);
1904 // this will also stuck in the holding cell
1905 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1906 check_added_monitors!(nodes[0], 0);
1907 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1908 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1910 // flush the pending htlc
1911 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1912 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1913 check_added_monitors!(nodes[1], 1);
1915 // the pending htlc should be promoted to committed
1916 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1917 check_added_monitors!(nodes[0], 1);
1918 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1920 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1921 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1922 // No commitment_signed so get_event_msg's assert(len == 1) passes
1923 check_added_monitors!(nodes[0], 1);
1925 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1926 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1927 check_added_monitors!(nodes[1], 1);
1929 expect_pending_htlcs_forwardable!(nodes[1]);
1931 let ref payment_event_11 = expect_forward!(nodes[1]);
1932 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1933 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1935 expect_pending_htlcs_forwardable!(nodes[2]);
1936 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1938 // flush the htlcs in the holding cell
1939 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1940 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1942 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1943 expect_pending_htlcs_forwardable!(nodes[1]);
1945 let ref payment_event_3 = expect_forward!(nodes[1]);
1946 assert_eq!(payment_event_3.msgs.len(), 2);
1947 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1948 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1950 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1951 expect_pending_htlcs_forwardable!(nodes[2]);
1953 let events = nodes[2].node.get_and_clear_pending_events();
1954 assert_eq!(events.len(), 2);
1956 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1957 assert_eq!(our_payment_hash_21, *payment_hash);
1958 assert_eq!(recv_value_21, amount_msat);
1959 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1960 assert_eq!(via_channel_id, Some(chan_2.2));
1962 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1963 assert!(payment_preimage.is_none());
1964 assert_eq!(our_payment_secret_21, *payment_secret);
1966 _ => panic!("expected PaymentPurpose::InvoicePayment")
1969 _ => panic!("Unexpected event"),
1972 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1973 assert_eq!(our_payment_hash_22, *payment_hash);
1974 assert_eq!(recv_value_22, amount_msat);
1975 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1976 assert_eq!(via_channel_id, Some(chan_2.2));
1978 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1979 assert!(payment_preimage.is_none());
1980 assert_eq!(our_payment_secret_22, *payment_secret);
1982 _ => panic!("expected PaymentPurpose::InvoicePayment")
1985 _ => panic!("Unexpected event"),
1988 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1989 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1990 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1992 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1993 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1994 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1996 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1997 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);
1998 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1999 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2000 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2002 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2003 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2007 fn channel_reserve_in_flight_removes() {
2008 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2009 // can send to its counterparty, but due to update ordering, the other side may not yet have
2010 // considered those HTLCs fully removed.
2011 // This tests that we don't count HTLCs which will not be included in the next remote
2012 // commitment transaction towards the reserve value (as it implies no commitment transaction
2013 // will be generated which violates the remote reserve value).
2014 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2016 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2017 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2018 // you only consider the value of the first HTLC, it may not),
2019 // * start routing a third HTLC from A to B,
2020 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2021 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2022 // * deliver the first fulfill from B
2023 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2025 // * deliver A's response CS and RAA.
2026 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2027 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2028 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2029 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2030 let chanmon_cfgs = create_chanmon_cfgs(2);
2031 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2032 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2033 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2034 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2036 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2037 // Route the first two HTLCs.
2038 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2039 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2040 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2042 // Start routing the third HTLC (this is just used to get everyone in the right state).
2043 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2045 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2046 check_added_monitors!(nodes[0], 1);
2047 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2048 assert_eq!(events.len(), 1);
2049 SendEvent::from_event(events.remove(0))
2052 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2053 // initial fulfill/CS.
2054 nodes[1].node.claim_funds(payment_preimage_1);
2055 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2056 check_added_monitors!(nodes[1], 1);
2057 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2059 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2060 // remove the second HTLC when we send the HTLC back from B to A.
2061 nodes[1].node.claim_funds(payment_preimage_2);
2062 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2063 check_added_monitors!(nodes[1], 1);
2064 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2066 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2067 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2068 check_added_monitors!(nodes[0], 1);
2069 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2070 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2072 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2073 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2074 check_added_monitors!(nodes[1], 1);
2075 // B is already AwaitingRAA, so cant generate a CS here
2076 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2078 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2079 check_added_monitors!(nodes[1], 1);
2080 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2082 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2083 check_added_monitors!(nodes[0], 1);
2084 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2086 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2087 check_added_monitors!(nodes[1], 1);
2088 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2090 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2091 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2092 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2093 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2094 // on-chain as necessary).
2095 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2096 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2097 check_added_monitors!(nodes[0], 1);
2098 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2099 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2101 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2102 check_added_monitors!(nodes[1], 1);
2103 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2105 expect_pending_htlcs_forwardable!(nodes[1]);
2106 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2108 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2109 // resolve the second HTLC from A's point of view.
2110 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2111 check_added_monitors!(nodes[0], 1);
2112 expect_payment_path_successful!(nodes[0]);
2113 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2115 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2116 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2117 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2119 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2120 check_added_monitors!(nodes[1], 1);
2121 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2122 assert_eq!(events.len(), 1);
2123 SendEvent::from_event(events.remove(0))
2126 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2127 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2128 check_added_monitors!(nodes[0], 1);
2129 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2131 // Now just resolve all the outstanding messages/HTLCs for completeness...
2133 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2134 check_added_monitors!(nodes[1], 1);
2135 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2137 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2138 check_added_monitors!(nodes[1], 1);
2140 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2141 check_added_monitors!(nodes[0], 1);
2142 expect_payment_path_successful!(nodes[0]);
2143 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2145 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2146 check_added_monitors!(nodes[1], 1);
2147 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2149 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2150 check_added_monitors!(nodes[0], 1);
2152 expect_pending_htlcs_forwardable!(nodes[0]);
2153 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2155 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2156 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2160 fn channel_monitor_network_test() {
2161 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2162 // tests that ChannelMonitor is able to recover from various states.
2163 let chanmon_cfgs = create_chanmon_cfgs(5);
2164 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2165 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2166 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2168 // Create some initial channels
2169 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2170 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2171 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2172 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2174 // Make sure all nodes are at the same starting height
2175 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2176 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2177 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2178 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2179 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2181 // Rebalance the network a bit by relaying one payment through all the channels...
2182 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2183 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2184 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2185 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2187 // Simple case with no pending HTLCs:
2188 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2189 check_added_monitors!(nodes[1], 1);
2190 check_closed_broadcast!(nodes[1], true);
2192 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2193 assert_eq!(node_txn.len(), 1);
2194 mine_transaction(&nodes[0], &node_txn[0]);
2195 check_added_monitors!(nodes[0], 1);
2196 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2198 check_closed_broadcast!(nodes[0], true);
2199 assert_eq!(nodes[0].node.list_channels().len(), 0);
2200 assert_eq!(nodes[1].node.list_channels().len(), 1);
2201 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2202 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2204 // One pending HTLC is discarded by the force-close:
2205 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2207 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2208 // broadcasted until we reach the timelock time).
2209 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2210 check_closed_broadcast!(nodes[1], true);
2211 check_added_monitors!(nodes[1], 1);
2213 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2214 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2215 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2216 mine_transaction(&nodes[2], &node_txn[0]);
2217 check_added_monitors!(nodes[2], 1);
2218 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2220 check_closed_broadcast!(nodes[2], true);
2221 assert_eq!(nodes[1].node.list_channels().len(), 0);
2222 assert_eq!(nodes[2].node.list_channels().len(), 1);
2223 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2224 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2226 macro_rules! claim_funds {
2227 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2229 $node.node.claim_funds($preimage);
2230 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2231 check_added_monitors!($node, 1);
2233 let events = $node.node.get_and_clear_pending_msg_events();
2234 assert_eq!(events.len(), 1);
2236 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2237 assert!(update_add_htlcs.is_empty());
2238 assert!(update_fail_htlcs.is_empty());
2239 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2241 _ => panic!("Unexpected event"),
2247 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2248 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2249 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2250 check_added_monitors!(nodes[2], 1);
2251 check_closed_broadcast!(nodes[2], true);
2252 let node2_commitment_txid;
2254 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2255 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2256 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2257 node2_commitment_txid = node_txn[0].txid();
2259 // Claim the payment on nodes[3], giving it knowledge of the preimage
2260 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2261 mine_transaction(&nodes[3], &node_txn[0]);
2262 check_added_monitors!(nodes[3], 1);
2263 check_preimage_claim(&nodes[3], &node_txn);
2265 check_closed_broadcast!(nodes[3], true);
2266 assert_eq!(nodes[2].node.list_channels().len(), 0);
2267 assert_eq!(nodes[3].node.list_channels().len(), 1);
2268 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2269 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2271 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2272 // confusing us in the following tests.
2273 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2275 // One pending HTLC to time out:
2276 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2277 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2280 let (close_chan_update_1, close_chan_update_2) = {
2281 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2282 let events = nodes[3].node.get_and_clear_pending_msg_events();
2283 assert_eq!(events.len(), 2);
2284 let close_chan_update_1 = match events[0] {
2285 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2288 _ => panic!("Unexpected event"),
2291 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2292 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2294 _ => panic!("Unexpected event"),
2296 check_added_monitors!(nodes[3], 1);
2298 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2300 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2301 node_txn.retain(|tx| {
2302 if tx.input[0].previous_output.txid == node2_commitment_txid {
2308 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2310 // Claim the payment on nodes[4], giving it knowledge of the preimage
2311 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2313 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2314 let events = nodes[4].node.get_and_clear_pending_msg_events();
2315 assert_eq!(events.len(), 2);
2316 let close_chan_update_2 = match events[0] {
2317 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2320 _ => panic!("Unexpected event"),
2323 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2324 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2326 _ => panic!("Unexpected event"),
2328 check_added_monitors!(nodes[4], 1);
2329 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2331 mine_transaction(&nodes[4], &node_txn[0]);
2332 check_preimage_claim(&nodes[4], &node_txn);
2333 (close_chan_update_1, close_chan_update_2)
2335 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2336 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2337 assert_eq!(nodes[3].node.list_channels().len(), 0);
2338 assert_eq!(nodes[4].node.list_channels().len(), 0);
2340 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2341 ChannelMonitorUpdateStatus::Completed);
2342 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2343 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2347 fn test_justice_tx() {
2348 // Test justice txn built on revoked HTLC-Success tx, against both sides
2349 let mut alice_config = UserConfig::default();
2350 alice_config.channel_handshake_config.announced_channel = true;
2351 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2352 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2353 let mut bob_config = UserConfig::default();
2354 bob_config.channel_handshake_config.announced_channel = true;
2355 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2356 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2357 let user_cfgs = [Some(alice_config), Some(bob_config)];
2358 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2359 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2360 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2361 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2362 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2363 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2364 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2365 // Create some new channels:
2366 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2368 // A pending HTLC which will be revoked:
2369 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2370 // Get the will-be-revoked local txn from nodes[0]
2371 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2372 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2373 assert_eq!(revoked_local_txn[0].input.len(), 1);
2374 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2375 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2376 assert_eq!(revoked_local_txn[1].input.len(), 1);
2377 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2378 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2379 // Revoke the old state
2380 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2383 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2385 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2386 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2387 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2389 check_spends!(node_txn[0], revoked_local_txn[0]);
2390 node_txn.swap_remove(0);
2392 check_added_monitors!(nodes[1], 1);
2393 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2394 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2396 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2397 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2398 // Verify broadcast of revoked HTLC-timeout
2399 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2400 check_added_monitors!(nodes[0], 1);
2401 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2402 // Broadcast revoked HTLC-timeout on node 1
2403 mine_transaction(&nodes[1], &node_txn[1]);
2404 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2406 get_announce_close_broadcast_events(&nodes, 0, 1);
2408 assert_eq!(nodes[0].node.list_channels().len(), 0);
2409 assert_eq!(nodes[1].node.list_channels().len(), 0);
2411 // We test justice_tx build by A on B's revoked HTLC-Success tx
2412 // Create some new channels:
2413 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2415 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2419 // A pending HTLC which will be revoked:
2420 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2421 // Get the will-be-revoked local txn from B
2422 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2423 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2424 assert_eq!(revoked_local_txn[0].input.len(), 1);
2425 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2426 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2427 // Revoke the old state
2428 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2430 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2432 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2433 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2434 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2436 check_spends!(node_txn[0], revoked_local_txn[0]);
2437 node_txn.swap_remove(0);
2439 check_added_monitors!(nodes[0], 1);
2440 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2442 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2443 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2444 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2445 check_added_monitors!(nodes[1], 1);
2446 mine_transaction(&nodes[0], &node_txn[1]);
2447 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2448 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2450 get_announce_close_broadcast_events(&nodes, 0, 1);
2451 assert_eq!(nodes[0].node.list_channels().len(), 0);
2452 assert_eq!(nodes[1].node.list_channels().len(), 0);
2456 fn revoked_output_claim() {
2457 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2458 // transaction is broadcast by its counterparty
2459 let chanmon_cfgs = create_chanmon_cfgs(2);
2460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2462 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2463 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2464 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2465 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2466 assert_eq!(revoked_local_txn.len(), 1);
2467 // Only output is the full channel value back to nodes[0]:
2468 assert_eq!(revoked_local_txn[0].output.len(), 1);
2469 // Send a payment through, updating everyone's latest commitment txn
2470 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2472 // Inform nodes[1] that nodes[0] broadcast a stale tx
2473 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2474 check_added_monitors!(nodes[1], 1);
2475 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2476 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2477 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2479 check_spends!(node_txn[0], revoked_local_txn[0]);
2481 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2482 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2483 get_announce_close_broadcast_events(&nodes, 0, 1);
2484 check_added_monitors!(nodes[0], 1);
2485 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2489 fn claim_htlc_outputs_shared_tx() {
2490 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2491 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2492 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2493 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2494 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2495 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2497 // Create some new channel:
2498 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2500 // Rebalance the network to generate htlc in the two directions
2501 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2502 // 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
2503 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2504 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2506 // Get the will-be-revoked local txn from node[0]
2507 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2508 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2509 assert_eq!(revoked_local_txn[0].input.len(), 1);
2510 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2511 assert_eq!(revoked_local_txn[1].input.len(), 1);
2512 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2513 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2514 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2516 //Revoke the old state
2517 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2520 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2521 check_added_monitors!(nodes[0], 1);
2522 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2523 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2524 check_added_monitors!(nodes[1], 1);
2525 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2526 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2527 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2529 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2530 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2532 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2533 check_spends!(node_txn[0], revoked_local_txn[0]);
2535 let mut witness_lens = BTreeSet::new();
2536 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2537 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2538 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2539 assert_eq!(witness_lens.len(), 3);
2540 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2541 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2542 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2544 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2545 // ANTI_REORG_DELAY confirmations.
2546 mine_transaction(&nodes[1], &node_txn[0]);
2547 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2548 expect_payment_failed!(nodes[1], payment_hash_2, false);
2550 get_announce_close_broadcast_events(&nodes, 0, 1);
2551 assert_eq!(nodes[0].node.list_channels().len(), 0);
2552 assert_eq!(nodes[1].node.list_channels().len(), 0);
2556 fn claim_htlc_outputs_single_tx() {
2557 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2558 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2559 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2560 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2561 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2562 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2564 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2566 // Rebalance the network to generate htlc in the two directions
2567 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2568 // 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
2569 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2570 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2571 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2573 // Get the will-be-revoked local txn from node[0]
2574 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2576 //Revoke the old state
2577 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2580 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2581 check_added_monitors!(nodes[0], 1);
2582 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2583 check_added_monitors!(nodes[1], 1);
2584 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2585 let mut events = nodes[0].node.get_and_clear_pending_events();
2586 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2587 match events.last().unwrap() {
2588 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2589 _ => panic!("Unexpected event"),
2592 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2593 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2595 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2596 assert_eq!(node_txn.len(), 7);
2598 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2599 assert_eq!(node_txn[0].input.len(), 1);
2600 check_spends!(node_txn[0], chan_1.3);
2601 assert_eq!(node_txn[1].input.len(), 1);
2602 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2603 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2604 check_spends!(node_txn[1], node_txn[0]);
2606 // Justice transactions are indices 2-3-4
2607 assert_eq!(node_txn[2].input.len(), 1);
2608 assert_eq!(node_txn[3].input.len(), 1);
2609 assert_eq!(node_txn[4].input.len(), 1);
2611 check_spends!(node_txn[2], revoked_local_txn[0]);
2612 check_spends!(node_txn[3], revoked_local_txn[0]);
2613 check_spends!(node_txn[4], revoked_local_txn[0]);
2615 let mut witness_lens = BTreeSet::new();
2616 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2617 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2618 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2619 assert_eq!(witness_lens.len(), 3);
2620 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2621 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2622 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2624 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2625 // ANTI_REORG_DELAY confirmations.
2626 mine_transaction(&nodes[1], &node_txn[2]);
2627 mine_transaction(&nodes[1], &node_txn[3]);
2628 mine_transaction(&nodes[1], &node_txn[4]);
2629 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2630 expect_payment_failed!(nodes[1], payment_hash_2, false);
2632 get_announce_close_broadcast_events(&nodes, 0, 1);
2633 assert_eq!(nodes[0].node.list_channels().len(), 0);
2634 assert_eq!(nodes[1].node.list_channels().len(), 0);
2638 fn test_htlc_on_chain_success() {
2639 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2640 // the preimage backward accordingly. So here we test that ChannelManager is
2641 // broadcasting the right event to other nodes in payment path.
2642 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2643 // A --------------------> B ----------------------> C (preimage)
2644 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2645 // commitment transaction was broadcast.
2646 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2648 // B should be able to claim via preimage if A then broadcasts its local tx.
2649 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2650 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2651 // PaymentSent event).
2653 let chanmon_cfgs = create_chanmon_cfgs(3);
2654 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2655 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2656 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2658 // Create some initial channels
2659 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2660 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2662 // Ensure all nodes are at the same height
2663 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2664 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2665 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2666 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2668 // Rebalance the network a bit by relaying one payment through all the channels...
2669 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2670 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2672 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2673 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2675 // Broadcast legit commitment tx from C on B's chain
2676 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2677 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2678 assert_eq!(commitment_tx.len(), 1);
2679 check_spends!(commitment_tx[0], chan_2.3);
2680 nodes[2].node.claim_funds(our_payment_preimage);
2681 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2682 nodes[2].node.claim_funds(our_payment_preimage_2);
2683 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2684 check_added_monitors!(nodes[2], 2);
2685 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2686 assert!(updates.update_add_htlcs.is_empty());
2687 assert!(updates.update_fail_htlcs.is_empty());
2688 assert!(updates.update_fail_malformed_htlcs.is_empty());
2689 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2691 mine_transaction(&nodes[2], &commitment_tx[0]);
2692 check_closed_broadcast!(nodes[2], true);
2693 check_added_monitors!(nodes[2], 1);
2694 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2695 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2696 assert_eq!(node_txn.len(), 2);
2697 check_spends!(node_txn[0], commitment_tx[0]);
2698 check_spends!(node_txn[1], commitment_tx[0]);
2699 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2700 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2701 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2702 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2703 assert_eq!(node_txn[0].lock_time.0, 0);
2704 assert_eq!(node_txn[1].lock_time.0, 0);
2706 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2707 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2708 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2709 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2711 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2712 assert_eq!(added_monitors.len(), 1);
2713 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2714 added_monitors.clear();
2716 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2717 assert_eq!(forwarded_events.len(), 3);
2718 match forwarded_events[0] {
2719 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2720 _ => panic!("Unexpected event"),
2722 let chan_id = Some(chan_1.2);
2723 match forwarded_events[1] {
2724 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2725 assert_eq!(fee_earned_msat, Some(1000));
2726 assert_eq!(prev_channel_id, chan_id);
2727 assert_eq!(claim_from_onchain_tx, true);
2728 assert_eq!(next_channel_id, Some(chan_2.2));
2732 match forwarded_events[2] {
2733 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2734 assert_eq!(fee_earned_msat, Some(1000));
2735 assert_eq!(prev_channel_id, chan_id);
2736 assert_eq!(claim_from_onchain_tx, true);
2737 assert_eq!(next_channel_id, Some(chan_2.2));
2741 let events = nodes[1].node.get_and_clear_pending_msg_events();
2743 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2744 assert_eq!(added_monitors.len(), 2);
2745 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2746 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2747 added_monitors.clear();
2749 assert_eq!(events.len(), 3);
2751 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2752 _ => panic!("Unexpected event"),
2755 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2756 _ => panic!("Unexpected event"),
2760 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, .. } } => {
2761 assert!(update_add_htlcs.is_empty());
2762 assert!(update_fail_htlcs.is_empty());
2763 assert_eq!(update_fulfill_htlcs.len(), 1);
2764 assert!(update_fail_malformed_htlcs.is_empty());
2765 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2767 _ => panic!("Unexpected event"),
2769 macro_rules! check_tx_local_broadcast {
2770 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2771 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2772 assert_eq!(node_txn.len(), 2);
2773 // Node[1]: 2 * HTLC-timeout tx
2774 // Node[0]: 2 * HTLC-timeout tx
2775 check_spends!(node_txn[0], $commitment_tx);
2776 check_spends!(node_txn[1], $commitment_tx);
2777 assert_ne!(node_txn[0].lock_time.0, 0);
2778 assert_ne!(node_txn[1].lock_time.0, 0);
2780 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2781 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2782 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2783 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2785 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2786 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2787 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2788 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2793 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2794 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2796 // Broadcast legit commitment tx from A on B's chain
2797 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2798 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2799 check_spends!(node_a_commitment_tx[0], chan_1.3);
2800 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2801 check_closed_broadcast!(nodes[1], true);
2802 check_added_monitors!(nodes[1], 1);
2803 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2804 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2805 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2806 let commitment_spend =
2807 if node_txn.len() == 1 {
2810 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2811 // FullBlockViaListen
2812 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2813 check_spends!(node_txn[1], commitment_tx[0]);
2814 check_spends!(node_txn[2], commitment_tx[0]);
2815 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2818 check_spends!(node_txn[0], commitment_tx[0]);
2819 check_spends!(node_txn[1], commitment_tx[0]);
2820 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2825 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2826 assert_eq!(commitment_spend.input.len(), 2);
2827 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2828 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2829 assert_eq!(commitment_spend.lock_time.0, 0);
2830 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2831 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2832 // we already checked the same situation with A.
2834 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2835 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2836 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2837 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2838 check_closed_broadcast!(nodes[0], true);
2839 check_added_monitors!(nodes[0], 1);
2840 let events = nodes[0].node.get_and_clear_pending_events();
2841 assert_eq!(events.len(), 5);
2842 let mut first_claimed = false;
2843 for event in events {
2845 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2846 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2847 assert!(!first_claimed);
2848 first_claimed = true;
2850 assert_eq!(payment_preimage, our_payment_preimage_2);
2851 assert_eq!(payment_hash, payment_hash_2);
2854 Event::PaymentPathSuccessful { .. } => {},
2855 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2856 _ => panic!("Unexpected event"),
2859 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2862 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2863 // Test that in case of a unilateral close onchain, we detect the state of output and
2864 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2865 // broadcasting the right event to other nodes in payment path.
2866 // A ------------------> B ----------------------> C (timeout)
2867 // B's commitment tx C's commitment tx
2869 // B's HTLC timeout tx B's timeout tx
2871 let chanmon_cfgs = create_chanmon_cfgs(3);
2872 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2873 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2874 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2875 *nodes[0].connect_style.borrow_mut() = connect_style;
2876 *nodes[1].connect_style.borrow_mut() = connect_style;
2877 *nodes[2].connect_style.borrow_mut() = connect_style;
2879 // Create some intial channels
2880 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2881 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2883 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2884 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2885 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2887 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2889 // Broadcast legit commitment tx from C on B's chain
2890 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2891 check_spends!(commitment_tx[0], chan_2.3);
2892 nodes[2].node.fail_htlc_backwards(&payment_hash);
2893 check_added_monitors!(nodes[2], 0);
2894 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2895 check_added_monitors!(nodes[2], 1);
2897 let events = nodes[2].node.get_and_clear_pending_msg_events();
2898 assert_eq!(events.len(), 1);
2900 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, .. } } => {
2901 assert!(update_add_htlcs.is_empty());
2902 assert!(!update_fail_htlcs.is_empty());
2903 assert!(update_fulfill_htlcs.is_empty());
2904 assert!(update_fail_malformed_htlcs.is_empty());
2905 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2907 _ => panic!("Unexpected event"),
2909 mine_transaction(&nodes[2], &commitment_tx[0]);
2910 check_closed_broadcast!(nodes[2], true);
2911 check_added_monitors!(nodes[2], 1);
2912 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2913 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2914 assert_eq!(node_txn.len(), 0);
2916 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2917 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2918 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2919 mine_transaction(&nodes[1], &commitment_tx[0]);
2920 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2923 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2924 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2926 check_spends!(node_txn[2], commitment_tx[0]);
2927 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2929 check_spends!(node_txn[0], chan_2.3);
2930 check_spends!(node_txn[1], node_txn[0]);
2931 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2932 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2934 timeout_tx = node_txn[2].clone();
2938 mine_transaction(&nodes[1], &timeout_tx);
2939 check_added_monitors!(nodes[1], 1);
2940 check_closed_broadcast!(nodes[1], true);
2942 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2944 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 }]);
2945 check_added_monitors!(nodes[1], 1);
2946 let events = nodes[1].node.get_and_clear_pending_msg_events();
2947 assert_eq!(events.len(), 1);
2949 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, .. } } => {
2950 assert!(update_add_htlcs.is_empty());
2951 assert!(!update_fail_htlcs.is_empty());
2952 assert!(update_fulfill_htlcs.is_empty());
2953 assert!(update_fail_malformed_htlcs.is_empty());
2954 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2956 _ => panic!("Unexpected event"),
2959 // Broadcast legit commitment tx from B on A's chain
2960 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2961 check_spends!(commitment_tx[0], chan_1.3);
2963 mine_transaction(&nodes[0], &commitment_tx[0]);
2964 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2966 check_closed_broadcast!(nodes[0], true);
2967 check_added_monitors!(nodes[0], 1);
2968 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2969 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2970 assert_eq!(node_txn.len(), 1);
2971 check_spends!(node_txn[0], commitment_tx[0]);
2972 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2976 fn test_htlc_on_chain_timeout() {
2977 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2978 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2979 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2983 fn test_simple_commitment_revoked_fail_backward() {
2984 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2985 // and fail backward accordingly.
2987 let chanmon_cfgs = create_chanmon_cfgs(3);
2988 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2989 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2990 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2992 // Create some initial channels
2993 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2994 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2996 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2997 // Get the will-be-revoked local txn from nodes[2]
2998 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2999 // Revoke the old state
3000 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3002 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3004 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3005 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3006 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3007 check_added_monitors!(nodes[1], 1);
3008 check_closed_broadcast!(nodes[1], true);
3010 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 }]);
3011 check_added_monitors!(nodes[1], 1);
3012 let events = nodes[1].node.get_and_clear_pending_msg_events();
3013 assert_eq!(events.len(), 1);
3015 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, .. } } => {
3016 assert!(update_add_htlcs.is_empty());
3017 assert_eq!(update_fail_htlcs.len(), 1);
3018 assert!(update_fulfill_htlcs.is_empty());
3019 assert!(update_fail_malformed_htlcs.is_empty());
3020 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3022 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3023 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3024 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3026 _ => panic!("Unexpected event"),
3030 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3031 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3032 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3033 // commitment transaction anymore.
3034 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3035 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3036 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3037 // technically disallowed and we should probably handle it reasonably.
3038 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3039 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3041 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3042 // commitment_signed (implying it will be in the latest remote commitment transaction).
3043 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3044 // and once they revoke the previous commitment transaction (allowing us to send a new
3045 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
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 mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3051 // Create some initial channels
3052 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3053 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3055 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 });
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 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3059 // Revoke the old state
3060 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3062 let value = if use_dust {
3063 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3064 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3065 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3068 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3069 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3070 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3072 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3073 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3074 check_added_monitors!(nodes[2], 1);
3075 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3076 assert!(updates.update_add_htlcs.is_empty());
3077 assert!(updates.update_fulfill_htlcs.is_empty());
3078 assert!(updates.update_fail_malformed_htlcs.is_empty());
3079 assert_eq!(updates.update_fail_htlcs.len(), 1);
3080 assert!(updates.update_fee.is_none());
3081 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3082 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3083 // Drop the last RAA from 3 -> 2
3085 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3086 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3087 check_added_monitors!(nodes[2], 1);
3088 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3089 assert!(updates.update_add_htlcs.is_empty());
3090 assert!(updates.update_fulfill_htlcs.is_empty());
3091 assert!(updates.update_fail_malformed_htlcs.is_empty());
3092 assert_eq!(updates.update_fail_htlcs.len(), 1);
3093 assert!(updates.update_fee.is_none());
3094 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3095 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3096 check_added_monitors!(nodes[1], 1);
3097 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3098 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3099 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3100 check_added_monitors!(nodes[2], 1);
3102 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3103 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3104 check_added_monitors!(nodes[2], 1);
3105 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3106 assert!(updates.update_add_htlcs.is_empty());
3107 assert!(updates.update_fulfill_htlcs.is_empty());
3108 assert!(updates.update_fail_malformed_htlcs.is_empty());
3109 assert_eq!(updates.update_fail_htlcs.len(), 1);
3110 assert!(updates.update_fee.is_none());
3111 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3112 // At this point first_payment_hash has dropped out of the latest two commitment
3113 // transactions that nodes[1] is tracking...
3114 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3115 check_added_monitors!(nodes[1], 1);
3116 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3117 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3118 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3119 check_added_monitors!(nodes[2], 1);
3121 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3122 // on nodes[2]'s RAA.
3123 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3124 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3125 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3126 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3127 check_added_monitors!(nodes[1], 0);
3130 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3131 // One monitor for the new revocation preimage, no second on as we won't generate a new
3132 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3133 check_added_monitors!(nodes[1], 1);
3134 let events = nodes[1].node.get_and_clear_pending_events();
3135 assert_eq!(events.len(), 2);
3137 Event::PendingHTLCsForwardable { .. } => { },
3138 _ => panic!("Unexpected event"),
3141 Event::HTLCHandlingFailed { .. } => { },
3142 _ => panic!("Unexpected event"),
3144 // Deliberately don't process the pending fail-back so they all fail back at once after
3145 // block connection just like the !deliver_bs_raa case
3148 let mut failed_htlcs = HashSet::new();
3149 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3151 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3152 check_added_monitors!(nodes[1], 1);
3153 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3155 let events = nodes[1].node.get_and_clear_pending_events();
3156 assert_eq!(events.len(), if deliver_bs_raa { 2 + nodes.len() - 1 } else { 3 + nodes.len() });
3158 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3159 _ => panic!("Unexepected event"),
3162 Event::PaymentPathFailed { ref payment_hash, .. } => {
3163 assert_eq!(*payment_hash, fourth_payment_hash);
3165 _ => panic!("Unexpected event"),
3167 if !deliver_bs_raa {
3169 Event::PendingHTLCsForwardable { .. } => { },
3170 _ => panic!("Unexpected event"),
3172 nodes[1].node.abandon_payment(PaymentId(fourth_payment_hash.0));
3173 let payment_failed_events = nodes[1].node.get_and_clear_pending_events();
3174 assert_eq!(payment_failed_events.len(), 1);
3175 match payment_failed_events[0] {
3176 Event::PaymentFailed { ref payment_hash, .. } => {
3177 assert_eq!(*payment_hash, fourth_payment_hash);
3179 _ => panic!("Unexpected event"),
3182 nodes[1].node.process_pending_htlc_forwards();
3183 check_added_monitors!(nodes[1], 1);
3185 let events = nodes[1].node.get_and_clear_pending_msg_events();
3186 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3187 match events[if deliver_bs_raa { 1 } else { 0 }] {
3188 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3189 _ => panic!("Unexpected event"),
3191 match events[if deliver_bs_raa { 2 } else { 1 }] {
3192 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3193 assert_eq!(channel_id, chan_2.2);
3194 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3196 _ => panic!("Unexpected event"),
3200 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, .. } } => {
3201 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3202 assert_eq!(update_add_htlcs.len(), 1);
3203 assert!(update_fulfill_htlcs.is_empty());
3204 assert!(update_fail_htlcs.is_empty());
3205 assert!(update_fail_malformed_htlcs.is_empty());
3207 _ => panic!("Unexpected event"),
3210 match events[if deliver_bs_raa { 3 } else { 2 }] {
3211 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, .. } } => {
3212 assert!(update_add_htlcs.is_empty());
3213 assert_eq!(update_fail_htlcs.len(), 3);
3214 assert!(update_fulfill_htlcs.is_empty());
3215 assert!(update_fail_malformed_htlcs.is_empty());
3216 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3218 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3219 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3220 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3222 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3224 let events = nodes[0].node.get_and_clear_pending_events();
3225 assert_eq!(events.len(), 3);
3227 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3228 assert!(failed_htlcs.insert(payment_hash.0));
3229 // If we delivered B's RAA we got an unknown preimage error, not something
3230 // that we should update our routing table for.
3231 if !deliver_bs_raa {
3232 assert!(network_update.is_some());
3235 _ => panic!("Unexpected event"),
3238 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3239 assert!(failed_htlcs.insert(payment_hash.0));
3240 assert!(network_update.is_some());
3242 _ => panic!("Unexpected event"),
3245 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3246 assert!(failed_htlcs.insert(payment_hash.0));
3247 assert!(network_update.is_some());
3249 _ => panic!("Unexpected event"),
3252 _ => panic!("Unexpected event"),
3255 assert!(failed_htlcs.contains(&first_payment_hash.0));
3256 assert!(failed_htlcs.contains(&second_payment_hash.0));
3257 assert!(failed_htlcs.contains(&third_payment_hash.0));
3261 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3262 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3263 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3264 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3265 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3269 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3270 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3271 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3272 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3273 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3277 fn fail_backward_pending_htlc_upon_channel_failure() {
3278 let chanmon_cfgs = create_chanmon_cfgs(2);
3279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3281 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3282 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3284 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3286 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3287 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3288 check_added_monitors!(nodes[0], 1);
3290 let payment_event = {
3291 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3292 assert_eq!(events.len(), 1);
3293 SendEvent::from_event(events.remove(0))
3295 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3296 assert_eq!(payment_event.msgs.len(), 1);
3299 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3300 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3302 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3303 check_added_monitors!(nodes[0], 0);
3305 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3308 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3310 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3312 let secp_ctx = Secp256k1::new();
3313 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3314 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3315 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3316 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3317 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3319 // Send a 0-msat update_add_htlc to fail the channel.
3320 let update_add_htlc = msgs::UpdateAddHTLC {
3326 onion_routing_packet,
3328 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3330 let events = nodes[0].node.get_and_clear_pending_events();
3331 assert_eq!(events.len(), 2);
3332 // Check that Alice fails backward the pending HTLC from the second payment.
3334 Event::PaymentPathFailed { payment_hash, .. } => {
3335 assert_eq!(payment_hash, failed_payment_hash);
3337 _ => panic!("Unexpected event"),
3340 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3341 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3343 _ => panic!("Unexpected event {:?}", events[1]),
3345 check_closed_broadcast!(nodes[0], true);
3346 check_added_monitors!(nodes[0], 1);
3350 fn test_htlc_ignore_latest_remote_commitment() {
3351 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3352 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3353 let chanmon_cfgs = create_chanmon_cfgs(2);
3354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3356 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3357 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3358 // We rely on the ability to connect a block redundantly, which isn't allowed via
3359 // `chain::Listen`, so we never run the test if we randomly get assigned that
3363 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3365 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3366 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3367 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3368 check_closed_broadcast!(nodes[0], true);
3369 check_added_monitors!(nodes[0], 1);
3370 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3372 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3373 assert_eq!(node_txn.len(), 3);
3374 assert_eq!(node_txn[0], node_txn[1]);
3376 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3377 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3378 check_closed_broadcast!(nodes[1], true);
3379 check_added_monitors!(nodes[1], 1);
3380 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3382 // Duplicate the connect_block call since this may happen due to other listeners
3383 // registering new transactions
3384 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3388 fn test_force_close_fail_back() {
3389 // Check which HTLCs are failed-backwards on channel force-closure
3390 let chanmon_cfgs = create_chanmon_cfgs(3);
3391 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3392 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3393 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3394 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3395 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3397 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3399 let mut payment_event = {
3400 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3401 check_added_monitors!(nodes[0], 1);
3403 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3404 assert_eq!(events.len(), 1);
3405 SendEvent::from_event(events.remove(0))
3408 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3409 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3411 expect_pending_htlcs_forwardable!(nodes[1]);
3413 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3414 assert_eq!(events_2.len(), 1);
3415 payment_event = SendEvent::from_event(events_2.remove(0));
3416 assert_eq!(payment_event.msgs.len(), 1);
3418 check_added_monitors!(nodes[1], 1);
3419 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3420 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3421 check_added_monitors!(nodes[2], 1);
3422 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3424 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3425 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3426 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3428 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3429 check_closed_broadcast!(nodes[2], true);
3430 check_added_monitors!(nodes[2], 1);
3431 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3433 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3434 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3435 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3436 // back to nodes[1] upon timeout otherwise.
3437 assert_eq!(node_txn.len(), 1);
3441 mine_transaction(&nodes[1], &tx);
3443 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3444 check_closed_broadcast!(nodes[1], true);
3445 check_added_monitors!(nodes[1], 1);
3446 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3448 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3450 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3451 .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);
3453 mine_transaction(&nodes[2], &tx);
3454 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3455 assert_eq!(node_txn.len(), 1);
3456 assert_eq!(node_txn[0].input.len(), 1);
3457 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3458 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3459 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3461 check_spends!(node_txn[0], tx);
3465 fn test_dup_events_on_peer_disconnect() {
3466 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3467 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3468 // as we used to generate the event immediately upon receipt of the payment preimage in the
3469 // update_fulfill_htlc message.
3471 let chanmon_cfgs = create_chanmon_cfgs(2);
3472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3475 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3477 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3479 nodes[1].node.claim_funds(payment_preimage);
3480 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3481 check_added_monitors!(nodes[1], 1);
3482 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3483 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3484 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3486 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3487 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3489 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3490 expect_payment_path_successful!(nodes[0]);
3494 fn test_peer_disconnected_before_funding_broadcasted() {
3495 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3496 // before the funding transaction has been broadcasted.
3497 let chanmon_cfgs = create_chanmon_cfgs(2);
3498 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3499 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3500 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3502 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3503 // broadcasted, even though it's created by `nodes[0]`.
3504 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();
3505 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3506 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3507 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3508 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3510 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3511 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3513 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3515 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3516 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3518 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3519 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3522 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3525 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3526 // disconnected before the funding transaction was broadcasted.
3527 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3528 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3530 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3531 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3535 fn test_simple_peer_disconnect() {
3536 // Test that we can reconnect when there are no lost messages
3537 let chanmon_cfgs = create_chanmon_cfgs(3);
3538 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3539 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3540 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3541 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3542 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3544 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3545 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3546 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3548 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3549 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3550 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3551 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3553 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3554 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3555 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3557 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3558 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3559 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3560 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3562 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3563 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3565 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3566 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3568 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3570 let events = nodes[0].node.get_and_clear_pending_events();
3571 assert_eq!(events.len(), 3);
3573 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3574 assert_eq!(payment_preimage, payment_preimage_3);
3575 assert_eq!(payment_hash, payment_hash_3);
3577 _ => panic!("Unexpected event"),
3580 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3581 assert_eq!(payment_hash, payment_hash_5);
3582 assert!(payment_failed_permanently);
3584 _ => panic!("Unexpected event"),
3587 Event::PaymentPathSuccessful { .. } => {},
3588 _ => panic!("Unexpected event"),
3592 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3593 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3596 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3597 // Test that we can reconnect when in-flight HTLC updates get dropped
3598 let chanmon_cfgs = create_chanmon_cfgs(2);
3599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3601 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3603 let mut as_channel_ready = None;
3604 let channel_id = if messages_delivered == 0 {
3605 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3606 as_channel_ready = Some(channel_ready);
3607 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3608 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3609 // it before the channel_reestablish message.
3612 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2
3615 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3617 let payment_event = {
3618 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3619 check_added_monitors!(nodes[0], 1);
3621 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3622 assert_eq!(events.len(), 1);
3623 SendEvent::from_event(events.remove(0))
3625 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3627 if messages_delivered < 2 {
3628 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3630 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3631 if messages_delivered >= 3 {
3632 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3633 check_added_monitors!(nodes[1], 1);
3634 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3636 if messages_delivered >= 4 {
3637 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3638 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3639 check_added_monitors!(nodes[0], 1);
3641 if messages_delivered >= 5 {
3642 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3643 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3644 // No commitment_signed so get_event_msg's assert(len == 1) passes
3645 check_added_monitors!(nodes[0], 1);
3647 if messages_delivered >= 6 {
3648 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3649 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3650 check_added_monitors!(nodes[1], 1);
3657 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3658 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3659 if messages_delivered < 3 {
3660 if simulate_broken_lnd {
3661 // lnd has a long-standing bug where they send a channel_ready prior to a
3662 // channel_reestablish if you reconnect prior to channel_ready time.
3664 // Here we simulate that behavior, delivering a channel_ready immediately on
3665 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3666 // in `reconnect_nodes` but we currently don't fail based on that.
3668 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3669 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3671 // Even if the channel_ready messages get exchanged, as long as nothing further was
3672 // received on either side, both sides will need to resend them.
3673 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3674 } else if messages_delivered == 3 {
3675 // nodes[0] still wants its RAA + commitment_signed
3676 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3677 } else if messages_delivered == 4 {
3678 // nodes[0] still wants its commitment_signed
3679 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3680 } else if messages_delivered == 5 {
3681 // nodes[1] still wants its final RAA
3682 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3683 } else if messages_delivered == 6 {
3684 // Everything was delivered...
3685 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3688 let events_1 = nodes[1].node.get_and_clear_pending_events();
3689 if messages_delivered == 0 {
3690 assert_eq!(events_1.len(), 2);
3692 Event::ChannelReady { .. } => { },
3693 _ => panic!("Unexpected event"),
3696 Event::PendingHTLCsForwardable { .. } => { },
3697 _ => panic!("Unexpected event"),
3700 assert_eq!(events_1.len(), 1);
3702 Event::PendingHTLCsForwardable { .. } => { },
3703 _ => panic!("Unexpected event"),
3707 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3708 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3709 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3711 nodes[1].node.process_pending_htlc_forwards();
3713 let events_2 = nodes[1].node.get_and_clear_pending_events();
3714 assert_eq!(events_2.len(), 1);
3716 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3717 assert_eq!(payment_hash_1, *payment_hash);
3718 assert_eq!(amount_msat, 1_000_000);
3719 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3720 assert_eq!(via_channel_id, Some(channel_id));
3722 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3723 assert!(payment_preimage.is_none());
3724 assert_eq!(payment_secret_1, *payment_secret);
3726 _ => panic!("expected PaymentPurpose::InvoicePayment")
3729 _ => panic!("Unexpected event"),
3732 nodes[1].node.claim_funds(payment_preimage_1);
3733 check_added_monitors!(nodes[1], 1);
3734 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3736 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3737 assert_eq!(events_3.len(), 1);
3738 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3739 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3740 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3741 assert!(updates.update_add_htlcs.is_empty());
3742 assert!(updates.update_fail_htlcs.is_empty());
3743 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3744 assert!(updates.update_fail_malformed_htlcs.is_empty());
3745 assert!(updates.update_fee.is_none());
3746 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3748 _ => panic!("Unexpected event"),
3751 if messages_delivered >= 1 {
3752 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3754 let events_4 = nodes[0].node.get_and_clear_pending_events();
3755 assert_eq!(events_4.len(), 1);
3757 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3758 assert_eq!(payment_preimage_1, *payment_preimage);
3759 assert_eq!(payment_hash_1, *payment_hash);
3761 _ => panic!("Unexpected event"),
3764 if messages_delivered >= 2 {
3765 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3766 check_added_monitors!(nodes[0], 1);
3767 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3769 if messages_delivered >= 3 {
3770 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3771 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3772 check_added_monitors!(nodes[1], 1);
3774 if messages_delivered >= 4 {
3775 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3776 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3777 // No commitment_signed so get_event_msg's assert(len == 1) passes
3778 check_added_monitors!(nodes[1], 1);
3780 if messages_delivered >= 5 {
3781 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3782 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3783 check_added_monitors!(nodes[0], 1);
3790 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3791 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3792 if messages_delivered < 2 {
3793 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3794 if messages_delivered < 1 {
3795 expect_payment_sent!(nodes[0], payment_preimage_1);
3797 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3799 } else if messages_delivered == 2 {
3800 // nodes[0] still wants its RAA + commitment_signed
3801 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3802 } else if messages_delivered == 3 {
3803 // nodes[0] still wants its commitment_signed
3804 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3805 } else if messages_delivered == 4 {
3806 // nodes[1] still wants its final RAA
3807 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3808 } else if messages_delivered == 5 {
3809 // Everything was delivered...
3810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3813 if messages_delivered == 1 || messages_delivered == 2 {
3814 expect_payment_path_successful!(nodes[0]);
3817 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3818 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3819 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3821 if messages_delivered > 2 {
3822 expect_payment_path_successful!(nodes[0]);
3825 // Channel should still work fine...
3826 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3827 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3828 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3832 fn test_drop_messages_peer_disconnect_a() {
3833 do_test_drop_messages_peer_disconnect(0, true);
3834 do_test_drop_messages_peer_disconnect(0, false);
3835 do_test_drop_messages_peer_disconnect(1, false);
3836 do_test_drop_messages_peer_disconnect(2, false);
3840 fn test_drop_messages_peer_disconnect_b() {
3841 do_test_drop_messages_peer_disconnect(3, false);
3842 do_test_drop_messages_peer_disconnect(4, false);
3843 do_test_drop_messages_peer_disconnect(5, false);
3844 do_test_drop_messages_peer_disconnect(6, false);
3848 fn test_channel_ready_without_best_block_updated() {
3849 // Previously, if we were offline when a funding transaction was locked in, and then we came
3850 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3851 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3852 // channel_ready immediately instead.
3853 let chanmon_cfgs = create_chanmon_cfgs(2);
3854 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3855 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3856 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3857 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3859 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3861 let conf_height = nodes[0].best_block_info().1 + 1;
3862 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3863 let block_txn = [funding_tx];
3864 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3865 let conf_block_header = nodes[0].get_block_header(conf_height);
3866 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3868 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3869 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3870 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3874 fn test_drop_messages_peer_disconnect_dual_htlc() {
3875 // Test that we can handle reconnecting when both sides of a channel have pending
3876 // commitment_updates when we disconnect.
3877 let chanmon_cfgs = create_chanmon_cfgs(2);
3878 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3879 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3880 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3881 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3883 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3885 // Now try to send a second payment which will fail to send
3886 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3887 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3888 check_added_monitors!(nodes[0], 1);
3890 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3891 assert_eq!(events_1.len(), 1);
3893 MessageSendEvent::UpdateHTLCs { .. } => {},
3894 _ => panic!("Unexpected event"),
3897 nodes[1].node.claim_funds(payment_preimage_1);
3898 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3899 check_added_monitors!(nodes[1], 1);
3901 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3902 assert_eq!(events_2.len(), 1);
3904 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 } } => {
3905 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3906 assert!(update_add_htlcs.is_empty());
3907 assert_eq!(update_fulfill_htlcs.len(), 1);
3908 assert!(update_fail_htlcs.is_empty());
3909 assert!(update_fail_malformed_htlcs.is_empty());
3910 assert!(update_fee.is_none());
3912 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3913 let events_3 = nodes[0].node.get_and_clear_pending_events();
3914 assert_eq!(events_3.len(), 1);
3916 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3917 assert_eq!(*payment_preimage, payment_preimage_1);
3918 assert_eq!(*payment_hash, payment_hash_1);
3920 _ => panic!("Unexpected event"),
3923 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3924 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3925 // No commitment_signed so get_event_msg's assert(len == 1) passes
3926 check_added_monitors!(nodes[0], 1);
3928 _ => panic!("Unexpected event"),
3931 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3932 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3934 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3935 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3936 assert_eq!(reestablish_1.len(), 1);
3937 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3938 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3939 assert_eq!(reestablish_2.len(), 1);
3941 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3942 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3943 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3944 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3946 assert!(as_resp.0.is_none());
3947 assert!(bs_resp.0.is_none());
3949 assert!(bs_resp.1.is_none());
3950 assert!(bs_resp.2.is_none());
3952 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3954 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3955 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3956 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3957 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3958 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3959 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3960 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3961 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3962 // No commitment_signed so get_event_msg's assert(len == 1) passes
3963 check_added_monitors!(nodes[1], 1);
3965 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3966 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3967 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3968 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3969 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3970 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3971 assert!(bs_second_commitment_signed.update_fee.is_none());
3972 check_added_monitors!(nodes[1], 1);
3974 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3975 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3976 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3977 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3978 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3979 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3980 assert!(as_commitment_signed.update_fee.is_none());
3981 check_added_monitors!(nodes[0], 1);
3983 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3984 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3985 // No commitment_signed so get_event_msg's assert(len == 1) passes
3986 check_added_monitors!(nodes[0], 1);
3988 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3989 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3990 // No commitment_signed so get_event_msg's assert(len == 1) passes
3991 check_added_monitors!(nodes[1], 1);
3993 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3994 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3995 check_added_monitors!(nodes[1], 1);
3997 expect_pending_htlcs_forwardable!(nodes[1]);
3999 let events_5 = nodes[1].node.get_and_clear_pending_events();
4000 assert_eq!(events_5.len(), 1);
4002 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4003 assert_eq!(payment_hash_2, *payment_hash);
4005 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4006 assert!(payment_preimage.is_none());
4007 assert_eq!(payment_secret_2, *payment_secret);
4009 _ => panic!("expected PaymentPurpose::InvoicePayment")
4012 _ => panic!("Unexpected event"),
4015 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4016 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4017 check_added_monitors!(nodes[0], 1);
4019 expect_payment_path_successful!(nodes[0]);
4020 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4023 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4024 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4025 // to avoid our counterparty failing the channel.
4026 let chanmon_cfgs = create_chanmon_cfgs(2);
4027 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4028 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4029 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4031 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4033 let our_payment_hash = if send_partial_mpp {
4034 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4035 // Use the utility function send_payment_along_path to send the payment with MPP data which
4036 // indicates there are more HTLCs coming.
4037 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.
4038 let payment_id = PaymentId([42; 32]);
4039 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4040 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
4041 check_added_monitors!(nodes[0], 1);
4042 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4043 assert_eq!(events.len(), 1);
4044 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4045 // hop should *not* yet generate any PaymentClaimable event(s).
4046 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4049 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4052 let mut block = Block {
4053 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4056 connect_block(&nodes[0], &block);
4057 connect_block(&nodes[1], &block);
4058 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4059 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4060 block.header.prev_blockhash = block.block_hash();
4061 connect_block(&nodes[0], &block);
4062 connect_block(&nodes[1], &block);
4065 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4067 check_added_monitors!(nodes[1], 1);
4068 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4069 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4070 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4071 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4072 assert!(htlc_timeout_updates.update_fee.is_none());
4074 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4075 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4076 // 100_000 msat as u64, followed by the height at which we failed back above
4077 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4078 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4079 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4083 fn test_htlc_timeout() {
4084 do_test_htlc_timeout(true);
4085 do_test_htlc_timeout(false);
4088 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4089 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4090 let chanmon_cfgs = create_chanmon_cfgs(3);
4091 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4092 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4093 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4094 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4095 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4097 // Make sure all nodes are at the same starting height
4098 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4099 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4100 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4102 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4103 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4105 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4107 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4108 check_added_monitors!(nodes[1], 1);
4110 // Now attempt to route a second payment, which should be placed in the holding cell
4111 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4112 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4113 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4115 check_added_monitors!(nodes[0], 1);
4116 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4117 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4118 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4119 expect_pending_htlcs_forwardable!(nodes[1]);
4121 check_added_monitors!(nodes[1], 0);
4123 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4124 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4125 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4126 connect_blocks(&nodes[1], 1);
4129 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 }]);
4130 check_added_monitors!(nodes[1], 1);
4131 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4132 assert_eq!(fail_commit.len(), 1);
4133 match fail_commit[0] {
4134 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4135 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4136 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4138 _ => unreachable!(),
4140 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4142 expect_payment_failed!(nodes[1], second_payment_hash, false);
4147 fn test_holding_cell_htlc_add_timeouts() {
4148 do_test_holding_cell_htlc_add_timeouts(false);
4149 do_test_holding_cell_htlc_add_timeouts(true);
4152 macro_rules! check_spendable_outputs {
4153 ($node: expr, $keysinterface: expr) => {
4155 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4156 let mut txn = Vec::new();
4157 let mut all_outputs = Vec::new();
4158 let secp_ctx = Secp256k1::new();
4159 for event in events.drain(..) {
4161 Event::SpendableOutputs { mut outputs } => {
4162 for outp in outputs.drain(..) {
4163 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4164 all_outputs.push(outp);
4167 _ => panic!("Unexpected event"),
4170 if all_outputs.len() > 1 {
4171 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, &secp_ctx) {
4181 fn test_claim_sizeable_push_msat() {
4182 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4183 let chanmon_cfgs = create_chanmon_cfgs(2);
4184 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4185 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4186 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4188 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4189 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4190 check_closed_broadcast!(nodes[1], true);
4191 check_added_monitors!(nodes[1], 1);
4192 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4193 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4194 assert_eq!(node_txn.len(), 1);
4195 check_spends!(node_txn[0], chan.3);
4196 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
4198 mine_transaction(&nodes[1], &node_txn[0]);
4199 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4201 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4202 assert_eq!(spend_txn.len(), 1);
4203 assert_eq!(spend_txn[0].input.len(), 1);
4204 check_spends!(spend_txn[0], node_txn[0]);
4205 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4209 fn test_claim_on_remote_sizeable_push_msat() {
4210 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4211 // to_remote output is encumbered by a P2WPKH
4212 let chanmon_cfgs = create_chanmon_cfgs(2);
4213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4215 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4217 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4218 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4219 check_closed_broadcast!(nodes[0], true);
4220 check_added_monitors!(nodes[0], 1);
4221 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4223 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4224 assert_eq!(node_txn.len(), 1);
4225 check_spends!(node_txn[0], chan.3);
4226 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
4228 mine_transaction(&nodes[1], &node_txn[0]);
4229 check_closed_broadcast!(nodes[1], true);
4230 check_added_monitors!(nodes[1], 1);
4231 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4232 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4234 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4235 assert_eq!(spend_txn.len(), 1);
4236 check_spends!(spend_txn[0], node_txn[0]);
4240 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4241 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4242 // to_remote output is encumbered by a P2WPKH
4244 let chanmon_cfgs = create_chanmon_cfgs(2);
4245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4247 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4249 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4250 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4251 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4252 assert_eq!(revoked_local_txn[0].input.len(), 1);
4253 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4255 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4256 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4257 check_closed_broadcast!(nodes[1], true);
4258 check_added_monitors!(nodes[1], 1);
4259 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4261 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4262 mine_transaction(&nodes[1], &node_txn[0]);
4263 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4265 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4266 assert_eq!(spend_txn.len(), 3);
4267 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4268 check_spends!(spend_txn[1], node_txn[0]);
4269 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4273 fn test_static_spendable_outputs_preimage_tx() {
4274 let chanmon_cfgs = create_chanmon_cfgs(2);
4275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4277 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4279 // Create some initial channels
4280 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4282 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4284 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4285 assert_eq!(commitment_tx[0].input.len(), 1);
4286 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4288 // Settle A's commitment tx on B's chain
4289 nodes[1].node.claim_funds(payment_preimage);
4290 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4291 check_added_monitors!(nodes[1], 1);
4292 mine_transaction(&nodes[1], &commitment_tx[0]);
4293 check_added_monitors!(nodes[1], 1);
4294 let events = nodes[1].node.get_and_clear_pending_msg_events();
4296 MessageSendEvent::UpdateHTLCs { .. } => {},
4297 _ => panic!("Unexpected event"),
4300 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4301 _ => panic!("Unexepected event"),
4304 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4305 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4306 assert_eq!(node_txn.len(), 1);
4307 check_spends!(node_txn[0], commitment_tx[0]);
4308 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4310 mine_transaction(&nodes[1], &node_txn[0]);
4311 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4312 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4314 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4315 assert_eq!(spend_txn.len(), 1);
4316 check_spends!(spend_txn[0], node_txn[0]);
4320 fn test_static_spendable_outputs_timeout_tx() {
4321 let chanmon_cfgs = create_chanmon_cfgs(2);
4322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4324 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4326 // Create some initial channels
4327 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4329 // Rebalance the network a bit by relaying one payment through all the channels ...
4330 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4332 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4334 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4335 assert_eq!(commitment_tx[0].input.len(), 1);
4336 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4338 // Settle A's commitment tx on B' chain
4339 mine_transaction(&nodes[1], &commitment_tx[0]);
4340 check_added_monitors!(nodes[1], 1);
4341 let events = nodes[1].node.get_and_clear_pending_msg_events();
4343 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4344 _ => panic!("Unexpected event"),
4346 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4348 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4349 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4350 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4351 check_spends!(node_txn[0], commitment_tx[0].clone());
4352 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4354 mine_transaction(&nodes[1], &node_txn[0]);
4355 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4356 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4357 expect_payment_failed!(nodes[1], our_payment_hash, false);
4359 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4360 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4361 check_spends!(spend_txn[0], commitment_tx[0]);
4362 check_spends!(spend_txn[1], node_txn[0]);
4363 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4367 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4368 let chanmon_cfgs = create_chanmon_cfgs(2);
4369 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4370 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4371 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4373 // Create some initial channels
4374 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4376 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4377 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4378 assert_eq!(revoked_local_txn[0].input.len(), 1);
4379 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4381 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4383 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4384 check_closed_broadcast!(nodes[1], true);
4385 check_added_monitors!(nodes[1], 1);
4386 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4388 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4389 assert_eq!(node_txn.len(), 1);
4390 assert_eq!(node_txn[0].input.len(), 2);
4391 check_spends!(node_txn[0], revoked_local_txn[0]);
4393 mine_transaction(&nodes[1], &node_txn[0]);
4394 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4396 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4397 assert_eq!(spend_txn.len(), 1);
4398 check_spends!(spend_txn[0], node_txn[0]);
4402 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4403 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4404 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4407 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4409 // Create some initial channels
4410 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4412 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4413 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4414 assert_eq!(revoked_local_txn[0].input.len(), 1);
4415 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4417 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4419 // A will generate HTLC-Timeout from revoked commitment tx
4420 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4421 check_closed_broadcast!(nodes[0], true);
4422 check_added_monitors!(nodes[0], 1);
4423 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4424 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4426 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4427 assert_eq!(revoked_htlc_txn.len(), 1);
4428 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4429 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4430 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4431 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4433 // B will generate justice tx from A's revoked commitment/HTLC tx
4434 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4435 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4436 check_closed_broadcast!(nodes[1], true);
4437 check_added_monitors!(nodes[1], 1);
4438 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4440 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4441 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4442 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4443 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4444 // transactions next...
4445 assert_eq!(node_txn[0].input.len(), 3);
4446 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4448 assert_eq!(node_txn[1].input.len(), 2);
4449 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4450 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4451 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4453 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4454 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4457 mine_transaction(&nodes[1], &node_txn[1]);
4458 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4460 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4461 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4462 assert_eq!(spend_txn.len(), 1);
4463 assert_eq!(spend_txn[0].input.len(), 1);
4464 check_spends!(spend_txn[0], node_txn[1]);
4468 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4469 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4470 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4471 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4472 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4473 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4475 // Create some initial channels
4476 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4478 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4479 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4480 assert_eq!(revoked_local_txn[0].input.len(), 1);
4481 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4483 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4484 assert_eq!(revoked_local_txn[0].output.len(), 2);
4486 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4488 // B will generate HTLC-Success from revoked commitment tx
4489 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4490 check_closed_broadcast!(nodes[1], true);
4491 check_added_monitors!(nodes[1], 1);
4492 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4493 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4495 assert_eq!(revoked_htlc_txn.len(), 1);
4496 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4497 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4498 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4500 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4501 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4502 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4504 // A will generate justice tx from B's revoked commitment/HTLC tx
4505 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4506 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4507 check_closed_broadcast!(nodes[0], true);
4508 check_added_monitors!(nodes[0], 1);
4509 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4511 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4512 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4514 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4515 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4516 // transactions next...
4517 assert_eq!(node_txn[0].input.len(), 2);
4518 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4519 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4520 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4522 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4523 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4526 assert_eq!(node_txn[1].input.len(), 1);
4527 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4529 mine_transaction(&nodes[0], &node_txn[1]);
4530 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4532 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4533 // didn't try to generate any new transactions.
4535 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4536 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4537 assert_eq!(spend_txn.len(), 3);
4538 assert_eq!(spend_txn[0].input.len(), 1);
4539 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4540 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4541 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4542 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4546 fn test_onchain_to_onchain_claim() {
4547 // Test that in case of channel closure, we detect the state of output and claim HTLC
4548 // on downstream peer's remote commitment tx.
4549 // First, have C claim an HTLC against its own latest commitment transaction.
4550 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4552 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4555 let chanmon_cfgs = create_chanmon_cfgs(3);
4556 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4557 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4558 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4560 // Create some initial channels
4561 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4562 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4564 // Ensure all nodes are at the same height
4565 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4566 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4567 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4568 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4570 // Rebalance the network a bit by relaying one payment through all the channels ...
4571 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4572 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4574 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4575 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4576 check_spends!(commitment_tx[0], chan_2.3);
4577 nodes[2].node.claim_funds(payment_preimage);
4578 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4579 check_added_monitors!(nodes[2], 1);
4580 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4581 assert!(updates.update_add_htlcs.is_empty());
4582 assert!(updates.update_fail_htlcs.is_empty());
4583 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4584 assert!(updates.update_fail_malformed_htlcs.is_empty());
4586 mine_transaction(&nodes[2], &commitment_tx[0]);
4587 check_closed_broadcast!(nodes[2], true);
4588 check_added_monitors!(nodes[2], 1);
4589 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4591 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4592 assert_eq!(c_txn.len(), 1);
4593 check_spends!(c_txn[0], commitment_tx[0]);
4594 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4595 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4596 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4598 // 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
4599 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4600 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4601 check_added_monitors!(nodes[1], 1);
4602 let events = nodes[1].node.get_and_clear_pending_events();
4603 assert_eq!(events.len(), 2);
4605 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4606 _ => panic!("Unexpected event"),
4609 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4610 assert_eq!(fee_earned_msat, Some(1000));
4611 assert_eq!(prev_channel_id, Some(chan_1.2));
4612 assert_eq!(claim_from_onchain_tx, true);
4613 assert_eq!(next_channel_id, Some(chan_2.2));
4615 _ => panic!("Unexpected event"),
4617 check_added_monitors!(nodes[1], 1);
4618 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4619 assert_eq!(msg_events.len(), 3);
4620 match msg_events[0] {
4621 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4622 _ => panic!("Unexpected event"),
4624 match msg_events[1] {
4625 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4626 _ => panic!("Unexpected event"),
4628 match msg_events[2] {
4629 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, .. } } => {
4630 assert!(update_add_htlcs.is_empty());
4631 assert!(update_fail_htlcs.is_empty());
4632 assert_eq!(update_fulfill_htlcs.len(), 1);
4633 assert!(update_fail_malformed_htlcs.is_empty());
4634 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4636 _ => panic!("Unexpected event"),
4638 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4639 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4640 mine_transaction(&nodes[1], &commitment_tx[0]);
4641 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4642 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4643 // ChannelMonitor: HTLC-Success tx
4644 assert_eq!(b_txn.len(), 1);
4645 check_spends!(b_txn[0], commitment_tx[0]);
4646 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4647 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4648 assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
4650 check_closed_broadcast!(nodes[1], true);
4651 check_added_monitors!(nodes[1], 1);
4655 fn test_duplicate_payment_hash_one_failure_one_success() {
4656 // Topology : A --> B --> C --> D
4657 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4658 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4659 // we forward one of the payments onwards to D.
4660 let chanmon_cfgs = create_chanmon_cfgs(4);
4661 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4662 // When this test was written, the default base fee floated based on the HTLC count.
4663 // It is now fixed, so we simply set the fee to the expected value here.
4664 let mut config = test_default_channel_config();
4665 config.channel_config.forwarding_fee_base_msat = 196;
4666 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4667 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4668 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4670 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4671 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4672 create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4674 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4675 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4676 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4677 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4678 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4680 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4682 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
4683 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4684 // script push size limit so that the below script length checks match
4685 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4686 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
4687 .with_features(channelmanager::provided_invoice_features());
4688 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
4689 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
4691 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4692 assert_eq!(commitment_txn[0].input.len(), 1);
4693 check_spends!(commitment_txn[0], chan_2.3);
4695 mine_transaction(&nodes[1], &commitment_txn[0]);
4696 check_closed_broadcast!(nodes[1], true);
4697 check_added_monitors!(nodes[1], 1);
4698 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4699 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4701 let htlc_timeout_tx;
4702 { // Extract one of the two HTLC-Timeout transaction
4703 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4704 // ChannelMonitor: timeout tx * 2-or-3
4705 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4707 check_spends!(node_txn[0], commitment_txn[0]);
4708 assert_eq!(node_txn[0].input.len(), 1);
4710 if node_txn.len() > 2 {
4711 check_spends!(node_txn[1], commitment_txn[0]);
4712 assert_eq!(node_txn[1].input.len(), 1);
4713 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4715 check_spends!(node_txn[2], commitment_txn[0]);
4716 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4718 check_spends!(node_txn[1], commitment_txn[0]);
4719 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4722 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4723 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4724 if node_txn.len() > 2 {
4725 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4727 htlc_timeout_tx = node_txn[0].clone();
4730 nodes[2].node.claim_funds(our_payment_preimage);
4731 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4733 mine_transaction(&nodes[2], &commitment_txn[0]);
4734 check_added_monitors!(nodes[2], 2);
4735 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4736 let events = nodes[2].node.get_and_clear_pending_msg_events();
4738 MessageSendEvent::UpdateHTLCs { .. } => {},
4739 _ => panic!("Unexpected event"),
4742 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4743 _ => panic!("Unexepected event"),
4745 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4746 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4747 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4748 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4749 assert_eq!(htlc_success_txn[0].input.len(), 1);
4750 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4751 assert_eq!(htlc_success_txn[1].input.len(), 1);
4752 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4753 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4754 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4756 mine_transaction(&nodes[1], &htlc_timeout_tx);
4757 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4758 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 }]);
4759 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4760 assert!(htlc_updates.update_add_htlcs.is_empty());
4761 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4762 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4763 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4764 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4765 check_added_monitors!(nodes[1], 1);
4767 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4768 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4770 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4772 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4774 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4775 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
4776 // and nodes[2] fee) is rounded down and then claimed in full.
4777 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4778 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
4779 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4780 assert!(updates.update_add_htlcs.is_empty());
4781 assert!(updates.update_fail_htlcs.is_empty());
4782 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4783 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4784 assert!(updates.update_fail_malformed_htlcs.is_empty());
4785 check_added_monitors!(nodes[1], 1);
4787 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4788 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4790 let events = nodes[0].node.get_and_clear_pending_events();
4792 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4793 assert_eq!(*payment_preimage, our_payment_preimage);
4794 assert_eq!(*payment_hash, duplicate_payment_hash);
4796 _ => panic!("Unexpected event"),
4801 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4802 let chanmon_cfgs = create_chanmon_cfgs(2);
4803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4805 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4807 // Create some initial channels
4808 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4810 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4811 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4812 assert_eq!(local_txn.len(), 1);
4813 assert_eq!(local_txn[0].input.len(), 1);
4814 check_spends!(local_txn[0], chan_1.3);
4816 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4817 nodes[1].node.claim_funds(payment_preimage);
4818 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4819 check_added_monitors!(nodes[1], 1);
4821 mine_transaction(&nodes[1], &local_txn[0]);
4822 check_added_monitors!(nodes[1], 1);
4823 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4824 let events = nodes[1].node.get_and_clear_pending_msg_events();
4826 MessageSendEvent::UpdateHTLCs { .. } => {},
4827 _ => panic!("Unexpected event"),
4830 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4831 _ => panic!("Unexepected event"),
4834 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4835 assert_eq!(node_txn.len(), 1);
4836 assert_eq!(node_txn[0].input.len(), 1);
4837 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4838 check_spends!(node_txn[0], local_txn[0]);
4842 mine_transaction(&nodes[1], &node_tx);
4843 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4845 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4846 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4847 assert_eq!(spend_txn.len(), 1);
4848 assert_eq!(spend_txn[0].input.len(), 1);
4849 check_spends!(spend_txn[0], node_tx);
4850 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4853 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4854 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4855 // unrevoked commitment transaction.
4856 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4857 // a remote RAA before they could be failed backwards (and combinations thereof).
4858 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4859 // use the same payment hashes.
4860 // Thus, we use a six-node network:
4865 // And test where C fails back to A/B when D announces its latest commitment transaction
4866 let chanmon_cfgs = create_chanmon_cfgs(6);
4867 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4868 // When this test was written, the default base fee floated based on the HTLC count.
4869 // It is now fixed, so we simply set the fee to the expected value here.
4870 let mut config = test_default_channel_config();
4871 config.channel_config.forwarding_fee_base_msat = 196;
4872 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4873 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4874 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4876 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4877 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4878 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4879 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4880 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4882 // Rebalance and check output sanity...
4883 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4884 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4885 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4887 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4889 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
4891 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
4892 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4894 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).unwrap()); // not added < dust limit + HTLC tx fee
4896 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).unwrap()); // not added < dust limit + HTLC tx fee
4898 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4900 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4901 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4903 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).unwrap());
4905 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).unwrap());
4908 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4910 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4911 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).unwrap()); // not added < dust limit + HTLC tx fee
4914 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
4916 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4917 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).unwrap());
4919 // Double-check that six of the new HTLC were added
4920 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4921 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4922 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4923 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4925 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4926 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4927 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4928 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4929 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4930 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4931 check_added_monitors!(nodes[4], 0);
4933 let failed_destinations = vec![
4934 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4935 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4936 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
4937 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
4939 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
4940 check_added_monitors!(nodes[4], 1);
4942 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4943 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4944 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4945 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4946 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4947 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4949 // Fail 3rd below-dust and 7th above-dust HTLCs
4950 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
4951 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
4952 check_added_monitors!(nodes[5], 0);
4954 let failed_destinations_2 = vec![
4955 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
4956 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
4958 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
4959 check_added_monitors!(nodes[5], 1);
4961 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4962 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4963 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4964 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4966 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
4968 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
4969 let failed_destinations_3 = vec![
4970 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
4971 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
4972 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
4973 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
4974 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
4975 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
4977 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
4978 check_added_monitors!(nodes[3], 1);
4979 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4980 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4981 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4982 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4983 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4984 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4985 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4986 if deliver_last_raa {
4987 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4989 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4992 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4993 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4994 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4995 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4997 // We now broadcast the latest commitment transaction, which *should* result in failures for
4998 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4999 // the non-broadcast above-dust HTLCs.
5001 // Alternatively, we may broadcast the previous commitment transaction, which should only
5002 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5003 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5005 if announce_latest {
5006 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5008 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5010 let events = nodes[2].node.get_and_clear_pending_events();
5011 let close_event = if deliver_last_raa {
5012 assert_eq!(events.len(), 2 + 6);
5013 events.last().clone().unwrap()
5015 assert_eq!(events.len(), 1);
5016 events.last().clone().unwrap()
5019 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5020 _ => panic!("Unexpected event"),
5023 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5024 check_closed_broadcast!(nodes[2], true);
5025 if deliver_last_raa {
5026 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5028 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();
5029 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5031 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5032 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5034 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5037 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5039 check_added_monitors!(nodes[2], 3);
5041 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5042 assert_eq!(cs_msgs.len(), 2);
5043 let mut a_done = false;
5044 for msg in cs_msgs {
5046 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5047 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5048 // should be failed-backwards here.
5049 let target = if *node_id == nodes[0].node.get_our_node_id() {
5050 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5051 for htlc in &updates.update_fail_htlcs {
5052 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 });
5054 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5059 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5060 for htlc in &updates.update_fail_htlcs {
5061 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5063 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5064 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5067 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5068 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5069 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5070 if announce_latest {
5071 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5072 if *node_id == nodes[0].node.get_our_node_id() {
5073 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5076 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5078 _ => panic!("Unexpected event"),
5082 let as_events = nodes[0].node.get_and_clear_pending_events();
5083 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5084 let mut as_failds = HashSet::new();
5085 let mut as_updates = 0;
5086 for event in as_events.iter() {
5087 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5088 assert!(as_failds.insert(*payment_hash));
5089 if *payment_hash != payment_hash_2 {
5090 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5092 assert!(!payment_failed_permanently);
5094 if network_update.is_some() {
5097 } else { panic!("Unexpected event"); }
5099 assert!(as_failds.contains(&payment_hash_1));
5100 assert!(as_failds.contains(&payment_hash_2));
5101 if announce_latest {
5102 assert!(as_failds.contains(&payment_hash_3));
5103 assert!(as_failds.contains(&payment_hash_5));
5105 assert!(as_failds.contains(&payment_hash_6));
5107 let bs_events = nodes[1].node.get_and_clear_pending_events();
5108 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5109 let mut bs_failds = HashSet::new();
5110 let mut bs_updates = 0;
5111 for event in bs_events.iter() {
5112 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5113 assert!(bs_failds.insert(*payment_hash));
5114 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5115 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5117 assert!(!payment_failed_permanently);
5119 if network_update.is_some() {
5122 } else { panic!("Unexpected event"); }
5124 assert!(bs_failds.contains(&payment_hash_1));
5125 assert!(bs_failds.contains(&payment_hash_2));
5126 if announce_latest {
5127 assert!(bs_failds.contains(&payment_hash_4));
5129 assert!(bs_failds.contains(&payment_hash_5));
5131 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5132 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5133 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5134 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5135 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5136 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5140 fn test_fail_backwards_latest_remote_announce_a() {
5141 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5145 fn test_fail_backwards_latest_remote_announce_b() {
5146 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5150 fn test_fail_backwards_previous_remote_announce() {
5151 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5152 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5153 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5157 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5158 let chanmon_cfgs = create_chanmon_cfgs(2);
5159 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5160 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5161 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5163 // Create some initial channels
5164 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5166 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5167 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5168 assert_eq!(local_txn[0].input.len(), 1);
5169 check_spends!(local_txn[0], chan_1.3);
5171 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5172 mine_transaction(&nodes[0], &local_txn[0]);
5173 check_closed_broadcast!(nodes[0], true);
5174 check_added_monitors!(nodes[0], 1);
5175 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5176 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5178 let htlc_timeout = {
5179 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5180 assert_eq!(node_txn.len(), 1);
5181 assert_eq!(node_txn[0].input.len(), 1);
5182 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5183 check_spends!(node_txn[0], local_txn[0]);
5187 mine_transaction(&nodes[0], &htlc_timeout);
5188 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5189 expect_payment_failed!(nodes[0], our_payment_hash, false);
5191 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5192 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5193 assert_eq!(spend_txn.len(), 3);
5194 check_spends!(spend_txn[0], local_txn[0]);
5195 assert_eq!(spend_txn[1].input.len(), 1);
5196 check_spends!(spend_txn[1], htlc_timeout);
5197 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5198 assert_eq!(spend_txn[2].input.len(), 2);
5199 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5200 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5201 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5205 fn test_key_derivation_params() {
5206 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5207 // manager rotation to test that `channel_keys_id` returned in
5208 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5209 // then derive a `delayed_payment_key`.
5211 let chanmon_cfgs = create_chanmon_cfgs(3);
5213 // We manually create the node configuration to backup the seed.
5214 let seed = [42; 32];
5215 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5216 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);
5217 let network_graph = Arc::new(NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger));
5218 let router = test_utils::TestRouter::new(network_graph.clone());
5219 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, features: channelmanager::provided_init_features() };
5220 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5221 node_cfgs.remove(0);
5222 node_cfgs.insert(0, node);
5224 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5225 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5227 // Create some initial channels
5228 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5230 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5231 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5232 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5234 // Ensure all nodes are at the same height
5235 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5236 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5237 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5238 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5240 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5241 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5242 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5243 assert_eq!(local_txn_1[0].input.len(), 1);
5244 check_spends!(local_txn_1[0], chan_1.3);
5246 // We check funding pubkey are unique
5247 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]));
5248 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]));
5249 if from_0_funding_key_0 == from_1_funding_key_0
5250 || from_0_funding_key_0 == from_1_funding_key_1
5251 || from_0_funding_key_1 == from_1_funding_key_0
5252 || from_0_funding_key_1 == from_1_funding_key_1 {
5253 panic!("Funding pubkeys aren't unique");
5256 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5257 mine_transaction(&nodes[0], &local_txn_1[0]);
5258 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5259 check_closed_broadcast!(nodes[0], true);
5260 check_added_monitors!(nodes[0], 1);
5261 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5263 let htlc_timeout = {
5264 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5265 assert_eq!(node_txn.len(), 1);
5266 assert_eq!(node_txn[0].input.len(), 1);
5267 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5268 check_spends!(node_txn[0], local_txn_1[0]);
5272 mine_transaction(&nodes[0], &htlc_timeout);
5273 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5274 expect_payment_failed!(nodes[0], our_payment_hash, false);
5276 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5277 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5278 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5279 assert_eq!(spend_txn.len(), 3);
5280 check_spends!(spend_txn[0], local_txn_1[0]);
5281 assert_eq!(spend_txn[1].input.len(), 1);
5282 check_spends!(spend_txn[1], htlc_timeout);
5283 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5284 assert_eq!(spend_txn[2].input.len(), 2);
5285 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5286 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5287 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5291 fn test_static_output_closing_tx() {
5292 let chanmon_cfgs = create_chanmon_cfgs(2);
5293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5295 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5297 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5299 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5300 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5302 mine_transaction(&nodes[0], &closing_tx);
5303 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5304 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5306 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5307 assert_eq!(spend_txn.len(), 1);
5308 check_spends!(spend_txn[0], closing_tx);
5310 mine_transaction(&nodes[1], &closing_tx);
5311 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5312 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5314 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5315 assert_eq!(spend_txn.len(), 1);
5316 check_spends!(spend_txn[0], closing_tx);
5319 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5320 let chanmon_cfgs = create_chanmon_cfgs(2);
5321 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5322 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5323 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5324 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5326 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5328 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5329 // present in B's local commitment transaction, but none of A's commitment transactions.
5330 nodes[1].node.claim_funds(payment_preimage);
5331 check_added_monitors!(nodes[1], 1);
5332 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5334 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5335 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5336 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5338 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5339 check_added_monitors!(nodes[0], 1);
5340 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5341 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5342 check_added_monitors!(nodes[1], 1);
5344 let starting_block = nodes[1].best_block_info();
5345 let mut block = Block {
5346 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5349 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5350 connect_block(&nodes[1], &block);
5351 block.header.prev_blockhash = block.block_hash();
5353 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5354 check_closed_broadcast!(nodes[1], true);
5355 check_added_monitors!(nodes[1], 1);
5356 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5359 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5360 let chanmon_cfgs = create_chanmon_cfgs(2);
5361 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5362 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5363 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5364 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5366 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5367 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5368 check_added_monitors!(nodes[0], 1);
5370 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5372 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5373 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5374 // to "time out" the HTLC.
5376 let starting_block = nodes[1].best_block_info();
5377 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5379 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5380 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5381 header.prev_blockhash = header.block_hash();
5383 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5384 check_closed_broadcast!(nodes[0], true);
5385 check_added_monitors!(nodes[0], 1);
5386 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5389 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5390 let chanmon_cfgs = create_chanmon_cfgs(3);
5391 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5392 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5393 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5394 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5396 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5397 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5398 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5399 // actually revoked.
5400 let htlc_value = if use_dust { 50000 } else { 3000000 };
5401 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5402 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5403 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5404 check_added_monitors!(nodes[1], 1);
5406 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5407 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5408 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5409 check_added_monitors!(nodes[0], 1);
5410 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5411 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5412 check_added_monitors!(nodes[1], 1);
5413 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5414 check_added_monitors!(nodes[1], 1);
5415 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5417 if check_revoke_no_close {
5418 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5419 check_added_monitors!(nodes[0], 1);
5422 let starting_block = nodes[1].best_block_info();
5423 let mut block = Block {
5424 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5427 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5428 connect_block(&nodes[0], &block);
5429 block.header.prev_blockhash = block.block_hash();
5431 if !check_revoke_no_close {
5432 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5433 check_closed_broadcast!(nodes[0], true);
5434 check_added_monitors!(nodes[0], 1);
5435 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5437 expect_payment_failed!(nodes[0], our_payment_hash, true);
5441 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5442 // There are only a few cases to test here:
5443 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5444 // broadcastable commitment transactions result in channel closure,
5445 // * its included in an unrevoked-but-previous remote commitment transaction,
5446 // * its included in the latest remote or local commitment transactions.
5447 // We test each of the three possible commitment transactions individually and use both dust and
5449 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5450 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5451 // tested for at least one of the cases in other tests.
5453 fn htlc_claim_single_commitment_only_a() {
5454 do_htlc_claim_local_commitment_only(true);
5455 do_htlc_claim_local_commitment_only(false);
5457 do_htlc_claim_current_remote_commitment_only(true);
5458 do_htlc_claim_current_remote_commitment_only(false);
5462 fn htlc_claim_single_commitment_only_b() {
5463 do_htlc_claim_previous_remote_commitment_only(true, false);
5464 do_htlc_claim_previous_remote_commitment_only(false, false);
5465 do_htlc_claim_previous_remote_commitment_only(true, true);
5466 do_htlc_claim_previous_remote_commitment_only(false, true);
5471 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5472 let chanmon_cfgs = create_chanmon_cfgs(2);
5473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5475 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5476 // Force duplicate randomness for every get-random call
5477 for node in nodes.iter() {
5478 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5481 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5482 let channel_value_satoshis=10000;
5483 let push_msat=10001;
5484 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5485 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5486 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5487 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5489 // Create a second channel with the same random values. This used to panic due to a colliding
5490 // channel_id, but now panics due to a colliding outbound SCID alias.
5491 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5495 fn bolt2_open_channel_sending_node_checks_part2() {
5496 let chanmon_cfgs = create_chanmon_cfgs(2);
5497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5499 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5501 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5502 let channel_value_satoshis=2^24;
5503 let push_msat=10001;
5504 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5506 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5507 let channel_value_satoshis=10000;
5508 // Test when push_msat is equal to 1000 * funding_satoshis.
5509 let push_msat=1000*channel_value_satoshis+1;
5510 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5512 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5513 let channel_value_satoshis=10000;
5514 let push_msat=10001;
5515 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
5516 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5517 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5519 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5520 // 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
5521 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5523 // 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.
5524 assert!(BREAKDOWN_TIMEOUT>0);
5525 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5527 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5528 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5529 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5531 // 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.
5532 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5533 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5534 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5535 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5536 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5540 fn bolt2_open_channel_sane_dust_limit() {
5541 let chanmon_cfgs = create_chanmon_cfgs(2);
5542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5544 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5546 let channel_value_satoshis=1000000;
5547 let push_msat=10001;
5548 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5549 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5550 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5551 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5553 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5554 let events = nodes[1].node.get_and_clear_pending_msg_events();
5555 let err_msg = match events[0] {
5556 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5559 _ => panic!("Unexpected event"),
5561 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5564 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5565 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5566 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5567 // is no longer affordable once it's freed.
5569 fn test_fail_holding_cell_htlc_upon_free() {
5570 let chanmon_cfgs = create_chanmon_cfgs(2);
5571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5573 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5574 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5576 // First nodes[0] generates an update_fee, setting the channel's
5577 // pending_update_fee.
5579 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5580 *feerate_lock += 20;
5582 nodes[0].node.timer_tick_occurred();
5583 check_added_monitors!(nodes[0], 1);
5585 let events = nodes[0].node.get_and_clear_pending_msg_events();
5586 assert_eq!(events.len(), 1);
5587 let (update_msg, commitment_signed) = match events[0] {
5588 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5589 (update_fee.as_ref(), commitment_signed)
5591 _ => panic!("Unexpected event"),
5594 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5596 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5597 let channel_reserve = chan_stat.channel_reserve_msat;
5598 let feerate = get_feerate!(nodes[0], chan.2);
5599 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
5601 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5602 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5603 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5605 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5606 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5607 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5608 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5610 // Flush the pending fee update.
5611 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5612 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5613 check_added_monitors!(nodes[1], 1);
5614 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5615 check_added_monitors!(nodes[0], 1);
5617 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5618 // HTLC, but now that the fee has been raised the payment will now fail, causing
5619 // us to surface its failure to the user.
5620 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5621 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5622 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);
5623 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5624 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5625 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5627 // Check that the payment failed to be sent out.
5628 let events = nodes[0].node.get_and_clear_pending_events();
5629 assert_eq!(events.len(), 1);
5631 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5632 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5633 assert_eq!(our_payment_hash.clone(), *payment_hash);
5634 assert_eq!(*payment_failed_permanently, false);
5635 assert_eq!(*all_paths_failed, true);
5636 assert_eq!(*network_update, None);
5637 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5639 _ => panic!("Unexpected event"),
5643 // Test that if multiple HTLCs are released from the holding cell and one is
5644 // valid but the other is no longer valid upon release, the valid HTLC can be
5645 // successfully completed while the other one fails as expected.
5647 fn test_free_and_fail_holding_cell_htlcs() {
5648 let chanmon_cfgs = create_chanmon_cfgs(2);
5649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5651 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5652 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5654 // First nodes[0] generates an update_fee, setting the channel's
5655 // pending_update_fee.
5657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5658 *feerate_lock += 200;
5660 nodes[0].node.timer_tick_occurred();
5661 check_added_monitors!(nodes[0], 1);
5663 let events = nodes[0].node.get_and_clear_pending_msg_events();
5664 assert_eq!(events.len(), 1);
5665 let (update_msg, commitment_signed) = match events[0] {
5666 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5667 (update_fee.as_ref(), commitment_signed)
5669 _ => panic!("Unexpected event"),
5672 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5674 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5675 let channel_reserve = chan_stat.channel_reserve_msat;
5676 let feerate = get_feerate!(nodes[0], chan.2);
5677 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
5679 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5681 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5682 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5683 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5685 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5686 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5687 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5688 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5689 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5690 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5691 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5692 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5694 // Flush the pending fee update.
5695 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5696 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5697 check_added_monitors!(nodes[1], 1);
5698 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5699 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5700 check_added_monitors!(nodes[0], 2);
5702 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5703 // but now that the fee has been raised the second payment will now fail, causing us
5704 // to surface its failure to the user. The first payment should succeed.
5705 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5706 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5707 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);
5708 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5709 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5710 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5712 // Check that the second payment failed to be sent out.
5713 let events = nodes[0].node.get_and_clear_pending_events();
5714 assert_eq!(events.len(), 1);
5716 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5717 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5718 assert_eq!(payment_hash_2.clone(), *payment_hash);
5719 assert_eq!(*payment_failed_permanently, false);
5720 assert_eq!(*all_paths_failed, true);
5721 assert_eq!(*network_update, None);
5722 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5724 _ => panic!("Unexpected event"),
5727 // Complete the first payment and the RAA from the fee update.
5728 let (payment_event, send_raa_event) = {
5729 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5730 assert_eq!(msgs.len(), 2);
5731 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5733 let raa = match send_raa_event {
5734 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5735 _ => panic!("Unexpected event"),
5737 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5738 check_added_monitors!(nodes[1], 1);
5739 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5740 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5741 let events = nodes[1].node.get_and_clear_pending_events();
5742 assert_eq!(events.len(), 1);
5744 Event::PendingHTLCsForwardable { .. } => {},
5745 _ => panic!("Unexpected event"),
5747 nodes[1].node.process_pending_htlc_forwards();
5748 let events = nodes[1].node.get_and_clear_pending_events();
5749 assert_eq!(events.len(), 1);
5751 Event::PaymentClaimable { .. } => {},
5752 _ => panic!("Unexpected event"),
5754 nodes[1].node.claim_funds(payment_preimage_1);
5755 check_added_monitors!(nodes[1], 1);
5756 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5758 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5759 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5760 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5761 expect_payment_sent!(nodes[0], payment_preimage_1);
5764 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5765 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5766 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5769 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5770 let chanmon_cfgs = create_chanmon_cfgs(3);
5771 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5772 // When this test was written, the default base fee floated based on the HTLC count.
5773 // It is now fixed, so we simply set the fee to the expected value here.
5774 let mut config = test_default_channel_config();
5775 config.channel_config.forwarding_fee_base_msat = 196;
5776 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5777 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5778 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5779 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5781 // First nodes[1] generates an update_fee, setting the channel's
5782 // pending_update_fee.
5784 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5785 *feerate_lock += 20;
5787 nodes[1].node.timer_tick_occurred();
5788 check_added_monitors!(nodes[1], 1);
5790 let events = nodes[1].node.get_and_clear_pending_msg_events();
5791 assert_eq!(events.len(), 1);
5792 let (update_msg, commitment_signed) = match events[0] {
5793 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5794 (update_fee.as_ref(), commitment_signed)
5796 _ => panic!("Unexpected event"),
5799 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5801 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
5802 let channel_reserve = chan_stat.channel_reserve_msat;
5803 let feerate = get_feerate!(nodes[0], chan_0_1.2);
5804 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
5806 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5808 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5809 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5810 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5811 let payment_event = {
5812 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5813 check_added_monitors!(nodes[0], 1);
5815 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5816 assert_eq!(events.len(), 1);
5818 SendEvent::from_event(events.remove(0))
5820 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5821 check_added_monitors!(nodes[1], 0);
5822 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5823 expect_pending_htlcs_forwardable!(nodes[1]);
5825 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
5826 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5828 // Flush the pending fee update.
5829 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5830 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5831 check_added_monitors!(nodes[2], 1);
5832 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5833 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5834 check_added_monitors!(nodes[1], 2);
5836 // A final RAA message is generated to finalize the fee update.
5837 let events = nodes[1].node.get_and_clear_pending_msg_events();
5838 assert_eq!(events.len(), 1);
5840 let raa_msg = match &events[0] {
5841 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5844 _ => panic!("Unexpected event"),
5847 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5848 check_added_monitors!(nodes[2], 1);
5849 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5851 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5852 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5853 assert_eq!(process_htlc_forwards_event.len(), 2);
5854 match &process_htlc_forwards_event[0] {
5855 &Event::PendingHTLCsForwardable { .. } => {},
5856 _ => panic!("Unexpected event"),
5859 // In response, we call ChannelManager's process_pending_htlc_forwards
5860 nodes[1].node.process_pending_htlc_forwards();
5861 check_added_monitors!(nodes[1], 1);
5863 // This causes the HTLC to be failed backwards.
5864 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5865 assert_eq!(fail_event.len(), 1);
5866 let (fail_msg, commitment_signed) = match &fail_event[0] {
5867 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5868 assert_eq!(updates.update_add_htlcs.len(), 0);
5869 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5870 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5871 assert_eq!(updates.update_fail_htlcs.len(), 1);
5872 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5874 _ => panic!("Unexpected event"),
5877 // Pass the failure messages back to nodes[0].
5878 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5879 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5881 // Complete the HTLC failure+removal process.
5882 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5883 check_added_monitors!(nodes[0], 1);
5884 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5885 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5886 check_added_monitors!(nodes[1], 2);
5887 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5888 assert_eq!(final_raa_event.len(), 1);
5889 let raa = match &final_raa_event[0] {
5890 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5891 _ => panic!("Unexpected event"),
5893 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5894 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5895 check_added_monitors!(nodes[0], 1);
5898 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5899 // 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.
5900 //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.
5903 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5904 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5905 let chanmon_cfgs = create_chanmon_cfgs(2);
5906 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5907 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5908 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5909 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5911 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5912 route.paths[0][0].fee_msat = 100;
5914 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
5915 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5916 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5917 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5921 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5922 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5923 let chanmon_cfgs = create_chanmon_cfgs(2);
5924 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5925 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5926 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5927 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5929 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5930 route.paths[0][0].fee_msat = 0;
5931 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
5932 assert_eq!(err, "Cannot send 0-msat HTLC"));
5934 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5935 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5939 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5940 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5941 let chanmon_cfgs = create_chanmon_cfgs(2);
5942 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5943 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5944 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5945 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5947 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5948 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5949 check_added_monitors!(nodes[0], 1);
5950 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5951 updates.update_add_htlcs[0].amount_msat = 0;
5953 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5954 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5955 check_closed_broadcast!(nodes[1], true).unwrap();
5956 check_added_monitors!(nodes[1], 1);
5957 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
5961 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5962 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5963 //It is enforced when constructing a route.
5964 let chanmon_cfgs = create_chanmon_cfgs(2);
5965 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5966 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5967 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5968 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5970 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
5971 .with_features(channelmanager::provided_invoice_features());
5972 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
5973 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
5974 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::InvalidRoute { ref err },
5975 assert_eq!(err, &"Channel CLTV overflowed?"));
5979 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5980 //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.
5981 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5982 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5983 let chanmon_cfgs = create_chanmon_cfgs(2);
5984 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5985 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5986 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5987 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5988 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
5990 for i in 0..max_accepted_htlcs {
5991 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5992 let payment_event = {
5993 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5994 check_added_monitors!(nodes[0], 1);
5996 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5997 assert_eq!(events.len(), 1);
5998 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5999 assert_eq!(htlcs[0].htlc_id, i);
6003 SendEvent::from_event(events.remove(0))
6005 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6006 check_added_monitors!(nodes[1], 0);
6007 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6009 expect_pending_htlcs_forwardable!(nodes[1]);
6010 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6012 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6013 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6014 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6016 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6017 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6021 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6022 //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.
6023 let chanmon_cfgs = create_chanmon_cfgs(2);
6024 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6025 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6026 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6027 let channel_value = 100000;
6028 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6029 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6031 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6033 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6034 // Manually create a route over our max in flight (which our router normally automatically
6036 route.paths[0][0].fee_msat = max_in_flight + 1;
6037 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6038 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6040 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6041 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
6043 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6046 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6048 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6049 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6050 let chanmon_cfgs = create_chanmon_cfgs(2);
6051 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6052 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6053 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6054 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6055 let htlc_minimum_msat: u64;
6057 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6058 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6059 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6062 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6063 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6064 check_added_monitors!(nodes[0], 1);
6065 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6066 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6067 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6068 assert!(nodes[1].node.list_channels().is_empty());
6069 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6070 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()));
6071 check_added_monitors!(nodes[1], 1);
6072 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6076 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6077 //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
6078 let chanmon_cfgs = create_chanmon_cfgs(2);
6079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6081 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6082 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6084 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6085 let channel_reserve = chan_stat.channel_reserve_msat;
6086 let feerate = get_feerate!(nodes[0], chan.2);
6087 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6088 // The 2* and +1 are for the fee spike reserve.
6089 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6091 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6092 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6093 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6094 check_added_monitors!(nodes[0], 1);
6095 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6097 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6098 // at this time channel-initiatee receivers are not required to enforce that senders
6099 // respect the fee_spike_reserve.
6100 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6101 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6103 assert!(nodes[1].node.list_channels().is_empty());
6104 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6105 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6106 check_added_monitors!(nodes[1], 1);
6107 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6111 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6112 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6113 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6114 let chanmon_cfgs = create_chanmon_cfgs(2);
6115 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6116 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6117 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6118 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6120 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6121 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6122 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6123 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6124 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6125 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6127 let mut msg = msgs::UpdateAddHTLC {
6131 payment_hash: our_payment_hash,
6132 cltv_expiry: htlc_cltv,
6133 onion_routing_packet: onion_packet.clone(),
6136 for i in 0..super::channel::OUR_MAX_HTLCS {
6137 msg.htlc_id = i as u64;
6138 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6140 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6141 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6143 assert!(nodes[1].node.list_channels().is_empty());
6144 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6145 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6146 check_added_monitors!(nodes[1], 1);
6147 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6151 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6152 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6153 let chanmon_cfgs = create_chanmon_cfgs(2);
6154 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6155 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6156 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6157 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6159 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6160 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6161 check_added_monitors!(nodes[0], 1);
6162 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6163 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6164 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6166 assert!(nodes[1].node.list_channels().is_empty());
6167 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6168 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6169 check_added_monitors!(nodes[1], 1);
6170 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6174 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6175 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6176 let chanmon_cfgs = create_chanmon_cfgs(2);
6177 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6178 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6179 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6181 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6182 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6183 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6184 check_added_monitors!(nodes[0], 1);
6185 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6186 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6187 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6189 assert!(nodes[1].node.list_channels().is_empty());
6190 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6191 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6192 check_added_monitors!(nodes[1], 1);
6193 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6197 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6198 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6199 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6200 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6201 let chanmon_cfgs = create_chanmon_cfgs(2);
6202 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6203 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6204 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6206 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6207 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6208 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6209 check_added_monitors!(nodes[0], 1);
6210 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6211 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6213 //Disconnect and Reconnect
6214 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6215 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6216 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6217 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6218 assert_eq!(reestablish_1.len(), 1);
6219 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6220 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6221 assert_eq!(reestablish_2.len(), 1);
6222 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6223 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6224 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6225 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6228 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6229 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6230 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6231 check_added_monitors!(nodes[1], 1);
6232 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6234 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6236 assert!(nodes[1].node.list_channels().is_empty());
6237 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6238 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6239 check_added_monitors!(nodes[1], 1);
6240 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6244 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6245 //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.
6247 let chanmon_cfgs = create_chanmon_cfgs(2);
6248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6250 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6251 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6252 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6253 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6255 check_added_monitors!(nodes[0], 1);
6256 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6257 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6259 let update_msg = msgs::UpdateFulfillHTLC{
6262 payment_preimage: our_payment_preimage,
6265 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6267 assert!(nodes[0].node.list_channels().is_empty());
6268 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6269 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()));
6270 check_added_monitors!(nodes[0], 1);
6271 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6275 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6276 //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.
6278 let chanmon_cfgs = create_chanmon_cfgs(2);
6279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6281 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6282 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6284 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6285 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6286 check_added_monitors!(nodes[0], 1);
6287 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6288 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6290 let update_msg = msgs::UpdateFailHTLC{
6293 reason: msgs::OnionErrorPacket { data: Vec::new()},
6296 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6298 assert!(nodes[0].node.list_channels().is_empty());
6299 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6300 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()));
6301 check_added_monitors!(nodes[0], 1);
6302 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6306 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6307 //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.
6309 let chanmon_cfgs = create_chanmon_cfgs(2);
6310 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6311 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6312 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6313 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6315 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6316 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6317 check_added_monitors!(nodes[0], 1);
6318 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6319 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6320 let update_msg = msgs::UpdateFailMalformedHTLC{
6323 sha256_of_onion: [1; 32],
6324 failure_code: 0x8000,
6327 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6329 assert!(nodes[0].node.list_channels().is_empty());
6330 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6331 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()));
6332 check_added_monitors!(nodes[0], 1);
6333 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6337 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6338 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6340 let chanmon_cfgs = create_chanmon_cfgs(2);
6341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6343 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6344 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6346 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6348 nodes[1].node.claim_funds(our_payment_preimage);
6349 check_added_monitors!(nodes[1], 1);
6350 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6352 let events = nodes[1].node.get_and_clear_pending_msg_events();
6353 assert_eq!(events.len(), 1);
6354 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6356 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, .. } } => {
6357 assert!(update_add_htlcs.is_empty());
6358 assert_eq!(update_fulfill_htlcs.len(), 1);
6359 assert!(update_fail_htlcs.is_empty());
6360 assert!(update_fail_malformed_htlcs.is_empty());
6361 assert!(update_fee.is_none());
6362 update_fulfill_htlcs[0].clone()
6364 _ => panic!("Unexpected event"),
6368 update_fulfill_msg.htlc_id = 1;
6370 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6372 assert!(nodes[0].node.list_channels().is_empty());
6373 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6374 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6375 check_added_monitors!(nodes[0], 1);
6376 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6380 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6381 //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.
6383 let chanmon_cfgs = create_chanmon_cfgs(2);
6384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6386 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6387 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6389 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6391 nodes[1].node.claim_funds(our_payment_preimage);
6392 check_added_monitors!(nodes[1], 1);
6393 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6395 let events = nodes[1].node.get_and_clear_pending_msg_events();
6396 assert_eq!(events.len(), 1);
6397 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6399 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, .. } } => {
6400 assert!(update_add_htlcs.is_empty());
6401 assert_eq!(update_fulfill_htlcs.len(), 1);
6402 assert!(update_fail_htlcs.is_empty());
6403 assert!(update_fail_malformed_htlcs.is_empty());
6404 assert!(update_fee.is_none());
6405 update_fulfill_htlcs[0].clone()
6407 _ => panic!("Unexpected event"),
6411 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6413 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6415 assert!(nodes[0].node.list_channels().is_empty());
6416 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6417 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6418 check_added_monitors!(nodes[0], 1);
6419 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6423 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6424 //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.
6426 let chanmon_cfgs = create_chanmon_cfgs(2);
6427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6430 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6432 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6433 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6434 check_added_monitors!(nodes[0], 1);
6436 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6437 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6439 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6440 check_added_monitors!(nodes[1], 0);
6441 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6443 let events = nodes[1].node.get_and_clear_pending_msg_events();
6445 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6447 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, .. } } => {
6448 assert!(update_add_htlcs.is_empty());
6449 assert!(update_fulfill_htlcs.is_empty());
6450 assert!(update_fail_htlcs.is_empty());
6451 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6452 assert!(update_fee.is_none());
6453 update_fail_malformed_htlcs[0].clone()
6455 _ => panic!("Unexpected event"),
6458 update_msg.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_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
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_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6470 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6471 // * 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.
6473 let chanmon_cfgs = create_chanmon_cfgs(3);
6474 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6475 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6476 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6477 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6478 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6480 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6483 let mut payment_event = {
6484 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6485 check_added_monitors!(nodes[0], 1);
6486 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6487 assert_eq!(events.len(), 1);
6488 SendEvent::from_event(events.remove(0))
6490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6491 check_added_monitors!(nodes[1], 0);
6492 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6493 expect_pending_htlcs_forwardable!(nodes[1]);
6494 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6495 assert_eq!(events_2.len(), 1);
6496 check_added_monitors!(nodes[1], 1);
6497 payment_event = SendEvent::from_event(events_2.remove(0));
6498 assert_eq!(payment_event.msgs.len(), 1);
6501 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6502 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6503 check_added_monitors!(nodes[2], 0);
6504 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6506 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6507 assert_eq!(events_3.len(), 1);
6508 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6510 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 } } => {
6511 assert!(update_add_htlcs.is_empty());
6512 assert!(update_fulfill_htlcs.is_empty());
6513 assert!(update_fail_htlcs.is_empty());
6514 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6515 assert!(update_fee.is_none());
6516 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6518 _ => panic!("Unexpected event"),
6522 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6524 check_added_monitors!(nodes[1], 0);
6525 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6526 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 }]);
6527 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6528 assert_eq!(events_4.len(), 1);
6530 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6532 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, .. } } => {
6533 assert!(update_add_htlcs.is_empty());
6534 assert!(update_fulfill_htlcs.is_empty());
6535 assert_eq!(update_fail_htlcs.len(), 1);
6536 assert!(update_fail_malformed_htlcs.is_empty());
6537 assert!(update_fee.is_none());
6539 _ => panic!("Unexpected event"),
6542 check_added_monitors!(nodes[1], 1);
6546 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6547 let chanmon_cfgs = create_chanmon_cfgs(3);
6548 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6549 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6550 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6551 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6552 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6554 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6557 let mut payment_event = {
6558 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6559 check_added_monitors!(nodes[0], 1);
6560 SendEvent::from_node(&nodes[0])
6563 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6564 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6565 expect_pending_htlcs_forwardable!(nodes[1]);
6566 check_added_monitors!(nodes[1], 1);
6567 payment_event = SendEvent::from_node(&nodes[1]);
6568 assert_eq!(payment_event.msgs.len(), 1);
6571 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6572 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6573 check_added_monitors!(nodes[2], 0);
6574 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6576 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6577 assert_eq!(events_3.len(), 1);
6579 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6580 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6581 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6582 update_msg.failure_code |= 0x2000;
6584 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6585 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6587 _ => panic!("Unexpected event"),
6590 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6591 vec![HTLCDestination::NextHopChannel {
6592 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6593 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6594 assert_eq!(events_4.len(), 1);
6595 check_added_monitors!(nodes[1], 1);
6598 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6599 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6600 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6602 _ => panic!("Unexpected event"),
6605 let events_5 = nodes[0].node.get_and_clear_pending_events();
6606 assert_eq!(events_5.len(), 1);
6608 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6609 // the node originating the error to its next hop.
6611 Event::PaymentPathFailed { network_update:
6612 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
6614 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6615 assert!(is_permanent);
6616 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6618 _ => panic!("Unexpected event"),
6621 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6624 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6625 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6626 // 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
6627 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6629 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6630 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6633 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6634 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6636 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6638 // We route 2 dust-HTLCs between A and B
6639 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6640 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6641 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6643 // Cache one local commitment tx as previous
6644 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6646 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6647 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6648 check_added_monitors!(nodes[1], 0);
6649 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6650 check_added_monitors!(nodes[1], 1);
6652 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6653 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6654 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6655 check_added_monitors!(nodes[0], 1);
6657 // Cache one local commitment tx as lastest
6658 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6660 let events = nodes[0].node.get_and_clear_pending_msg_events();
6662 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6663 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6665 _ => panic!("Unexpected event"),
6668 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6669 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6671 _ => panic!("Unexpected event"),
6674 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6675 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6676 if announce_latest {
6677 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6679 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6682 check_closed_broadcast!(nodes[0], true);
6683 check_added_monitors!(nodes[0], 1);
6684 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6686 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6687 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6688 let events = nodes[0].node.get_and_clear_pending_events();
6689 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6690 assert_eq!(events.len(), 2);
6691 let mut first_failed = false;
6692 for event in events {
6694 Event::PaymentPathFailed { payment_hash, .. } => {
6695 if payment_hash == payment_hash_1 {
6696 assert!(!first_failed);
6697 first_failed = true;
6699 assert_eq!(payment_hash, payment_hash_2);
6702 _ => panic!("Unexpected event"),
6708 fn test_failure_delay_dust_htlc_local_commitment() {
6709 do_test_failure_delay_dust_htlc_local_commitment(true);
6710 do_test_failure_delay_dust_htlc_local_commitment(false);
6713 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6714 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6715 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6716 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6717 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6718 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6719 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6721 let chanmon_cfgs = create_chanmon_cfgs(3);
6722 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6723 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6724 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6725 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6727 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6729 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6730 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6732 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6733 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6735 // We revoked bs_commitment_tx
6737 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6738 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6741 let mut timeout_tx = Vec::new();
6743 // We fail dust-HTLC 1 by broadcast of local commitment tx
6744 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6745 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6746 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6747 expect_payment_failed!(nodes[0], dust_hash, false);
6749 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6750 check_closed_broadcast!(nodes[0], true);
6751 check_added_monitors!(nodes[0], 1);
6752 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6753 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6754 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6755 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6756 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6757 mine_transaction(&nodes[0], &timeout_tx[0]);
6758 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6759 expect_payment_failed!(nodes[0], non_dust_hash, false);
6761 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6762 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6763 check_closed_broadcast!(nodes[0], true);
6764 check_added_monitors!(nodes[0], 1);
6765 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6766 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6768 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6769 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6770 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6771 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6772 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6773 // dust HTLC should have been failed.
6774 expect_payment_failed!(nodes[0], dust_hash, false);
6777 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6779 assert_eq!(timeout_tx[0].lock_time.0, 0);
6781 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6782 mine_transaction(&nodes[0], &timeout_tx[0]);
6783 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6784 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6785 expect_payment_failed!(nodes[0], non_dust_hash, false);
6790 fn test_sweep_outbound_htlc_failure_update() {
6791 do_test_sweep_outbound_htlc_failure_update(false, true);
6792 do_test_sweep_outbound_htlc_failure_update(false, false);
6793 do_test_sweep_outbound_htlc_failure_update(true, false);
6797 fn test_user_configurable_csv_delay() {
6798 // We test our channel constructors yield errors when we pass them absurd csv delay
6800 let mut low_our_to_self_config = UserConfig::default();
6801 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6802 let mut high_their_to_self_config = UserConfig::default();
6803 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6804 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6805 let chanmon_cfgs = create_chanmon_cfgs(2);
6806 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6807 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6808 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6810 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6811 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6812 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
6813 &low_our_to_self_config, 0, 42)
6816 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())); },
6817 _ => panic!("Unexpected event"),
6819 } else { assert!(false) }
6821 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6822 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6823 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6824 open_channel.to_self_delay = 200;
6825 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6826 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6827 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6830 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())); },
6831 _ => panic!("Unexpected event"),
6833 } else { assert!(false); }
6835 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6836 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6837 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6838 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6839 accept_channel.to_self_delay = 200;
6840 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
6842 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6844 &ErrorAction::SendErrorMessage { ref msg } => {
6845 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()));
6846 reason_msg = msg.data.clone();
6850 } else { panic!(); }
6851 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6853 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6854 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6855 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6856 open_channel.to_self_delay = 200;
6857 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6858 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6859 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6862 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())); },
6863 _ => panic!("Unexpected event"),
6865 } else { assert!(false); }
6869 fn test_check_htlc_underpaying() {
6870 // Send payment through A -> B but A is maliciously
6871 // sending a probe payment (i.e less than expected value0
6872 // to B, B should refuse payment.
6874 let chanmon_cfgs = create_chanmon_cfgs(2);
6875 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6876 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6877 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6879 // Create some initial channels
6880 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6882 let scorer = test_utils::TestScorer::with_penalty(0);
6883 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6884 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
6885 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
6886 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6887 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
6888 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6889 check_added_monitors!(nodes[0], 1);
6891 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6892 assert_eq!(events.len(), 1);
6893 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6894 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6895 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6897 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6898 // and then will wait a second random delay before failing the HTLC back:
6899 expect_pending_htlcs_forwardable!(nodes[1]);
6900 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6902 // Node 3 is expecting payment of 100_000 but received 10_000,
6903 // it should fail htlc like we didn't know the preimage.
6904 nodes[1].node.process_pending_htlc_forwards();
6906 let events = nodes[1].node.get_and_clear_pending_msg_events();
6907 assert_eq!(events.len(), 1);
6908 let (update_fail_htlc, commitment_signed) = match events[0] {
6909 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 } } => {
6910 assert!(update_add_htlcs.is_empty());
6911 assert!(update_fulfill_htlcs.is_empty());
6912 assert_eq!(update_fail_htlcs.len(), 1);
6913 assert!(update_fail_malformed_htlcs.is_empty());
6914 assert!(update_fee.is_none());
6915 (update_fail_htlcs[0].clone(), commitment_signed)
6917 _ => panic!("Unexpected event"),
6919 check_added_monitors!(nodes[1], 1);
6921 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6922 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6924 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
6925 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
6926 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
6927 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6931 fn test_announce_disable_channels() {
6932 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
6933 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6935 let chanmon_cfgs = create_chanmon_cfgs(2);
6936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6938 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6940 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6941 create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6942 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6945 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6946 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6948 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
6949 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
6950 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6951 assert_eq!(msg_events.len(), 3);
6952 let mut chans_disabled = HashMap::new();
6953 for e in msg_events {
6955 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6956 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
6957 // Check that each channel gets updated exactly once
6958 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
6959 panic!("Generated ChannelUpdate for wrong chan!");
6962 _ => panic!("Unexpected event"),
6966 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6967 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6968 assert_eq!(reestablish_1.len(), 3);
6969 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6970 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6971 assert_eq!(reestablish_2.len(), 3);
6973 // Reestablish chan_1
6974 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6975 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6976 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6977 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6978 // Reestablish chan_2
6979 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6980 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6981 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6982 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6983 // Reestablish chan_3
6984 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
6985 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6986 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
6987 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6989 nodes[0].node.timer_tick_occurred();
6990 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6991 nodes[0].node.timer_tick_occurred();
6992 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6993 assert_eq!(msg_events.len(), 3);
6994 for e in msg_events {
6996 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6997 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
6998 match chans_disabled.remove(&msg.contents.short_channel_id) {
6999 // Each update should have a higher timestamp than the previous one, replacing
7001 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7002 None => panic!("Generated ChannelUpdate for wrong chan!"),
7005 _ => panic!("Unexpected event"),
7008 // Check that each channel gets updated exactly once
7009 assert!(chans_disabled.is_empty());
7013 fn test_bump_penalty_txn_on_revoked_commitment() {
7014 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7015 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
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 nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7022 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7024 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7025 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7026 .with_features(channelmanager::provided_invoice_features());
7027 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7028 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7030 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7031 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7032 assert_eq!(revoked_txn[0].output.len(), 4);
7033 assert_eq!(revoked_txn[0].input.len(), 1);
7034 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7035 let revoked_txid = revoked_txn[0].txid();
7037 let mut penalty_sum = 0;
7038 for outp in revoked_txn[0].output.iter() {
7039 if outp.script_pubkey.is_v0_p2wsh() {
7040 penalty_sum += outp.value;
7044 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7045 let header_114 = connect_blocks(&nodes[1], 14);
7047 // Actually revoke tx by claiming a HTLC
7048 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7049 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7050 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7051 check_added_monitors!(nodes[1], 1);
7053 // One or more justice tx should have been broadcast, check it
7057 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7058 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7059 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7060 assert_eq!(node_txn[0].output.len(), 1);
7061 check_spends!(node_txn[0], revoked_txn[0]);
7062 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7063 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7064 penalty_1 = node_txn[0].txid();
7068 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7069 connect_blocks(&nodes[1], 15);
7070 let mut penalty_2 = penalty_1;
7071 let mut feerate_2 = 0;
7073 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7074 assert_eq!(node_txn.len(), 1);
7075 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7076 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7077 assert_eq!(node_txn[0].output.len(), 1);
7078 check_spends!(node_txn[0], revoked_txn[0]);
7079 penalty_2 = node_txn[0].txid();
7080 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7081 assert_ne!(penalty_2, penalty_1);
7082 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7083 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7084 // Verify 25% bump heuristic
7085 assert!(feerate_2 * 100 >= feerate_1 * 125);
7089 assert_ne!(feerate_2, 0);
7091 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7092 connect_blocks(&nodes[1], 1);
7094 let mut feerate_3 = 0;
7096 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7097 assert_eq!(node_txn.len(), 1);
7098 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7099 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7100 assert_eq!(node_txn[0].output.len(), 1);
7101 check_spends!(node_txn[0], revoked_txn[0]);
7102 penalty_3 = node_txn[0].txid();
7103 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7104 assert_ne!(penalty_3, penalty_2);
7105 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7106 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7107 // Verify 25% bump heuristic
7108 assert!(feerate_3 * 100 >= feerate_2 * 125);
7112 assert_ne!(feerate_3, 0);
7114 nodes[1].node.get_and_clear_pending_events();
7115 nodes[1].node.get_and_clear_pending_msg_events();
7119 fn test_bump_penalty_txn_on_revoked_htlcs() {
7120 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7121 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7123 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7124 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7125 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7126 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7127 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7129 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7130 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7131 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7132 let scorer = test_utils::TestScorer::with_penalty(0);
7133 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7134 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7135 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7136 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7137 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7138 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7139 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7140 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7142 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7143 assert_eq!(revoked_local_txn[0].input.len(), 1);
7144 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7146 // Revoke local commitment tx
7147 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7149 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7150 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7151 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7152 check_closed_broadcast!(nodes[1], true);
7153 check_added_monitors!(nodes[1], 1);
7154 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7155 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7157 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7158 assert_eq!(revoked_htlc_txn.len(), 2);
7160 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7161 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7162 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7164 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7165 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7166 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7167 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7169 // Broadcast set of revoked txn on A
7170 let hash_128 = connect_blocks(&nodes[0], 40);
7171 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7172 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7173 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7174 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7175 let events = nodes[0].node.get_and_clear_pending_events();
7176 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7177 match events.last().unwrap() {
7178 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7179 _ => panic!("Unexpected event"),
7185 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7186 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7187 // Verify claim tx are spending revoked HTLC txn
7189 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7190 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7191 // which are included in the same block (they are broadcasted because we scan the
7192 // transactions linearly and generate claims as we go, they likely should be removed in the
7194 assert_eq!(node_txn[0].input.len(), 1);
7195 check_spends!(node_txn[0], revoked_local_txn[0]);
7196 assert_eq!(node_txn[1].input.len(), 1);
7197 check_spends!(node_txn[1], revoked_local_txn[0]);
7198 assert_eq!(node_txn[2].input.len(), 1);
7199 check_spends!(node_txn[2], revoked_local_txn[0]);
7201 // Each of the three justice transactions claim a separate (single) output of the three
7202 // available, which we check here:
7203 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7204 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7205 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7207 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7208 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7210 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7211 // output, checked above).
7212 assert_eq!(node_txn[3].input.len(), 2);
7213 assert_eq!(node_txn[3].output.len(), 1);
7214 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7216 first = node_txn[3].txid();
7217 // Store both feerates for later comparison
7218 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7219 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7220 penalty_txn = vec![node_txn[2].clone()];
7224 // Connect one more block to see if bumped penalty are issued for HTLC txn
7225 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7226 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7227 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7228 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7230 // Few more blocks to confirm penalty txn
7231 connect_blocks(&nodes[0], 4);
7232 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7233 let header_144 = connect_blocks(&nodes[0], 9);
7235 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7236 assert_eq!(node_txn.len(), 1);
7238 assert_eq!(node_txn[0].input.len(), 2);
7239 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7240 // Verify bumped tx is different and 25% bump heuristic
7241 assert_ne!(first, node_txn[0].txid());
7242 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7243 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7244 assert!(feerate_2 * 100 > feerate_1 * 125);
7245 let txn = vec![node_txn[0].clone()];
7249 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7250 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7251 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7252 connect_blocks(&nodes[0], 20);
7254 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7255 // We verify than no new transaction has been broadcast because previously
7256 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7257 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7258 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7259 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7260 // up bumped justice generation.
7261 assert_eq!(node_txn.len(), 0);
7264 check_closed_broadcast!(nodes[0], true);
7265 check_added_monitors!(nodes[0], 1);
7269 fn test_bump_penalty_txn_on_remote_commitment() {
7270 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7271 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7274 // Provide preimage for one
7275 // Check aggregation
7277 let chanmon_cfgs = create_chanmon_cfgs(2);
7278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7280 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7282 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7283 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7284 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7286 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7287 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7288 assert_eq!(remote_txn[0].output.len(), 4);
7289 assert_eq!(remote_txn[0].input.len(), 1);
7290 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7292 // Claim a HTLC without revocation (provide B monitor with preimage)
7293 nodes[1].node.claim_funds(payment_preimage);
7294 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7295 mine_transaction(&nodes[1], &remote_txn[0]);
7296 check_added_monitors!(nodes[1], 2);
7297 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7299 // One or more claim tx should have been broadcast, check it
7303 let feerate_timeout;
7304 let feerate_preimage;
7306 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7307 // 3 transactions including:
7308 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7309 assert_eq!(node_txn.len(), 3);
7310 assert_eq!(node_txn[0].input.len(), 1);
7311 assert_eq!(node_txn[1].input.len(), 1);
7312 assert_eq!(node_txn[2].input.len(), 1);
7313 check_spends!(node_txn[0], remote_txn[0]);
7314 check_spends!(node_txn[1], remote_txn[0]);
7315 check_spends!(node_txn[2], remote_txn[0]);
7317 preimage = node_txn[0].txid();
7318 let index = node_txn[0].input[0].previous_output.vout;
7319 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7320 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7322 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7323 (node_txn[2].clone(), node_txn[1].clone())
7325 (node_txn[1].clone(), node_txn[2].clone())
7328 preimage_bump = preimage_bump_tx;
7329 check_spends!(preimage_bump, remote_txn[0]);
7330 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7332 timeout = timeout_tx.txid();
7333 let index = timeout_tx.input[0].previous_output.vout;
7334 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7335 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7339 assert_ne!(feerate_timeout, 0);
7340 assert_ne!(feerate_preimage, 0);
7342 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7343 connect_blocks(&nodes[1], 15);
7345 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7346 assert_eq!(node_txn.len(), 1);
7347 assert_eq!(node_txn[0].input.len(), 1);
7348 assert_eq!(preimage_bump.input.len(), 1);
7349 check_spends!(node_txn[0], remote_txn[0]);
7350 check_spends!(preimage_bump, remote_txn[0]);
7352 let index = preimage_bump.input[0].previous_output.vout;
7353 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7354 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7355 assert!(new_feerate * 100 > feerate_timeout * 125);
7356 assert_ne!(timeout, preimage_bump.txid());
7358 let index = node_txn[0].input[0].previous_output.vout;
7359 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7360 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7361 assert!(new_feerate * 100 > feerate_preimage * 125);
7362 assert_ne!(preimage, node_txn[0].txid());
7367 nodes[1].node.get_and_clear_pending_events();
7368 nodes[1].node.get_and_clear_pending_msg_events();
7372 fn test_counterparty_raa_skip_no_crash() {
7373 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7374 // commitment transaction, we would have happily carried on and provided them the next
7375 // commitment transaction based on one RAA forward. This would probably eventually have led to
7376 // channel closure, but it would not have resulted in funds loss. Still, our
7377 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7378 // check simply that the channel is closed in response to such an RAA, but don't check whether
7379 // we decide to punish our counterparty for revoking their funds (as we don't currently
7381 let chanmon_cfgs = create_chanmon_cfgs(2);
7382 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7383 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7384 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7385 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
7387 let per_commitment_secret;
7388 let next_per_commitment_point;
7390 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7391 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7393 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7395 // Make signer believe we got a counterparty signature, so that it allows the revocation
7396 keys.get_enforcement_state().last_holder_commitment -= 1;
7397 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7399 // Must revoke without gaps
7400 keys.get_enforcement_state().last_holder_commitment -= 1;
7401 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7403 keys.get_enforcement_state().last_holder_commitment -= 1;
7404 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7405 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7408 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7409 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7410 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7411 check_added_monitors!(nodes[1], 1);
7412 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7416 fn test_bump_txn_sanitize_tracking_maps() {
7417 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7418 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7420 let chanmon_cfgs = create_chanmon_cfgs(2);
7421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7422 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7423 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7425 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7426 // Lock HTLC in both directions
7427 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7428 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7430 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7431 assert_eq!(revoked_local_txn[0].input.len(), 1);
7432 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7434 // Revoke local commitment tx
7435 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7437 // Broadcast set of revoked txn on A
7438 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7439 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7440 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7442 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7443 check_closed_broadcast!(nodes[0], true);
7444 check_added_monitors!(nodes[0], 1);
7445 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7447 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7448 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7449 check_spends!(node_txn[0], revoked_local_txn[0]);
7450 check_spends!(node_txn[1], revoked_local_txn[0]);
7451 check_spends!(node_txn[2], revoked_local_txn[0]);
7452 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7456 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7457 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7458 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7460 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7461 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7462 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7467 fn test_pending_claimed_htlc_no_balance_underflow() {
7468 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7469 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7470 let chanmon_cfgs = create_chanmon_cfgs(2);
7471 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7472 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7473 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7474 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7476 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7477 nodes[1].node.claim_funds(payment_preimage);
7478 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7479 check_added_monitors!(nodes[1], 1);
7480 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7482 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7483 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7484 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7485 check_added_monitors!(nodes[0], 1);
7486 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7488 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7489 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7490 // can get our balance.
7492 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7493 // the public key of the only hop. This works around ChannelDetails not showing the
7494 // almost-claimed HTLC as available balance.
7495 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7496 route.payment_params = None; // This is all wrong, but unnecessary
7497 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7498 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7499 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7501 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7505 fn test_channel_conf_timeout() {
7506 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7507 // confirm within 2016 blocks, as recommended by BOLT 2.
7508 let chanmon_cfgs = create_chanmon_cfgs(2);
7509 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7510 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7511 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7513 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7515 // The outbound node should wait forever for confirmation:
7516 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7517 // copied here instead of directly referencing the constant.
7518 connect_blocks(&nodes[0], 2016);
7519 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7521 // The inbound node should fail the channel after exactly 2016 blocks
7522 connect_blocks(&nodes[1], 2015);
7523 check_added_monitors!(nodes[1], 0);
7524 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7526 connect_blocks(&nodes[1], 1);
7527 check_added_monitors!(nodes[1], 1);
7528 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7529 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7530 assert_eq!(close_ev.len(), 1);
7532 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7533 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7534 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7536 _ => panic!("Unexpected event"),
7541 fn test_override_channel_config() {
7542 let chanmon_cfgs = create_chanmon_cfgs(2);
7543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7545 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7547 // Node0 initiates a channel to node1 using the override config.
7548 let mut override_config = UserConfig::default();
7549 override_config.channel_handshake_config.our_to_self_delay = 200;
7551 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7553 // Assert the channel created by node0 is using the override config.
7554 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7555 assert_eq!(res.channel_flags, 0);
7556 assert_eq!(res.to_self_delay, 200);
7560 fn test_override_0msat_htlc_minimum() {
7561 let mut zero_config = UserConfig::default();
7562 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7563 let chanmon_cfgs = create_chanmon_cfgs(2);
7564 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7565 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7566 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7568 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7569 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7570 assert_eq!(res.htlc_minimum_msat, 1);
7572 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7573 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7574 assert_eq!(res.htlc_minimum_msat, 1);
7578 fn test_channel_update_has_correct_htlc_maximum_msat() {
7579 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7580 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7581 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7582 // 90% of the `channel_value`.
7583 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7585 let mut config_30_percent = UserConfig::default();
7586 config_30_percent.channel_handshake_config.announced_channel = true;
7587 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7588 let mut config_50_percent = UserConfig::default();
7589 config_50_percent.channel_handshake_config.announced_channel = true;
7590 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7591 let mut config_95_percent = UserConfig::default();
7592 config_95_percent.channel_handshake_config.announced_channel = true;
7593 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7594 let mut config_100_percent = UserConfig::default();
7595 config_100_percent.channel_handshake_config.announced_channel = true;
7596 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7598 let chanmon_cfgs = create_chanmon_cfgs(4);
7599 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7600 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)]);
7601 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7603 let channel_value_satoshis = 100000;
7604 let channel_value_msat = channel_value_satoshis * 1000;
7605 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7606 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7607 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7609 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7610 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7612 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7613 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7614 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7615 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7616 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7617 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7619 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7620 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7622 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7623 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7624 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7626 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7630 fn test_manually_accept_inbound_channel_request() {
7631 let mut manually_accept_conf = UserConfig::default();
7632 manually_accept_conf.manually_accept_inbound_channels = true;
7633 let chanmon_cfgs = create_chanmon_cfgs(2);
7634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7636 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7638 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7639 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7641 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7643 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7644 // accepting the inbound channel request.
7645 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7647 let events = nodes[1].node.get_and_clear_pending_events();
7649 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7650 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7652 _ => panic!("Unexpected event"),
7655 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7656 assert_eq!(accept_msg_ev.len(), 1);
7658 match accept_msg_ev[0] {
7659 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7660 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7662 _ => panic!("Unexpected event"),
7665 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7667 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7668 assert_eq!(close_msg_ev.len(), 1);
7670 let events = nodes[1].node.get_and_clear_pending_events();
7672 Event::ChannelClosed { user_channel_id, .. } => {
7673 assert_eq!(user_channel_id, 23);
7675 _ => panic!("Unexpected event"),
7680 fn test_manually_reject_inbound_channel_request() {
7681 let mut manually_accept_conf = UserConfig::default();
7682 manually_accept_conf.manually_accept_inbound_channels = true;
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(manually_accept_conf.clone())]);
7686 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7688 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7689 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7691 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7693 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7694 // rejecting the inbound channel request.
7695 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7697 let events = nodes[1].node.get_and_clear_pending_events();
7699 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7700 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7702 _ => panic!("Unexpected event"),
7705 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7706 assert_eq!(close_msg_ev.len(), 1);
7708 match close_msg_ev[0] {
7709 MessageSendEvent::HandleError { ref node_id, .. } => {
7710 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7712 _ => panic!("Unexpected event"),
7714 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7718 fn test_reject_funding_before_inbound_channel_accepted() {
7719 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7720 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7721 // the node operator before the counterparty sends a `FundingCreated` message. If a
7722 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7723 // and the channel should be closed.
7724 let mut manually_accept_conf = UserConfig::default();
7725 manually_accept_conf.manually_accept_inbound_channels = true;
7726 let chanmon_cfgs = create_chanmon_cfgs(2);
7727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7731 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7732 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7733 let temp_channel_id = res.temporary_channel_id;
7735 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7737 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7738 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7740 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7741 nodes[1].node.get_and_clear_pending_events();
7743 // Get the `AcceptChannel` message of `nodes[1]` without calling
7744 // `ChannelManager::accept_inbound_channel`, which generates a
7745 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7746 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7747 // succeed when `nodes[0]` is passed to it.
7748 let accept_chan_msg = {
7750 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
7751 channel.get_accept_channel_message()
7753 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
7755 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7757 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7758 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7760 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7761 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7763 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7764 assert_eq!(close_msg_ev.len(), 1);
7766 let expected_err = "FundingCreated message received before the channel was accepted";
7767 match close_msg_ev[0] {
7768 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7769 assert_eq!(msg.channel_id, temp_channel_id);
7770 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7771 assert_eq!(msg.data, expected_err);
7773 _ => panic!("Unexpected event"),
7776 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7780 fn test_can_not_accept_inbound_channel_twice() {
7781 let mut manually_accept_conf = UserConfig::default();
7782 manually_accept_conf.manually_accept_inbound_channels = true;
7783 let chanmon_cfgs = create_chanmon_cfgs(2);
7784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7788 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7789 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7791 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7793 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7794 // accepting the inbound channel request.
7795 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7797 let events = nodes[1].node.get_and_clear_pending_events();
7799 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7800 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7801 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7803 Err(APIError::APIMisuseError { err }) => {
7804 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7806 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7807 Err(_) => panic!("Unexpected Error"),
7810 _ => panic!("Unexpected event"),
7813 // Ensure that the channel wasn't closed after attempting to accept it twice.
7814 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7815 assert_eq!(accept_msg_ev.len(), 1);
7817 match accept_msg_ev[0] {
7818 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7819 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7821 _ => panic!("Unexpected event"),
7826 fn test_can_not_accept_unknown_inbound_channel() {
7827 let chanmon_cfg = create_chanmon_cfgs(2);
7828 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7829 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7830 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7832 let unknown_channel_id = [0; 32];
7833 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7835 Err(APIError::ChannelUnavailable { err }) => {
7836 assert_eq!(err, "Can't accept a channel that doesn't exist");
7838 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7839 Err(_) => panic!("Unexpected Error"),
7844 fn test_simple_mpp() {
7845 // Simple test of sending a multi-path payment.
7846 let chanmon_cfgs = create_chanmon_cfgs(4);
7847 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7848 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7849 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7851 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7852 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7853 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7854 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7856 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7857 let path = route.paths[0].clone();
7858 route.paths.push(path);
7859 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7860 route.paths[0][0].short_channel_id = chan_1_id;
7861 route.paths[0][1].short_channel_id = chan_3_id;
7862 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7863 route.paths[1][0].short_channel_id = chan_2_id;
7864 route.paths[1][1].short_channel_id = chan_4_id;
7865 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7866 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7870 fn test_preimage_storage() {
7871 // Simple test of payment preimage storage allowing no client-side storage to claim payments
7872 let chanmon_cfgs = create_chanmon_cfgs(2);
7873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7875 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7877 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7880 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
7881 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7882 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7883 check_added_monitors!(nodes[0], 1);
7884 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7885 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7886 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7887 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7889 // Note that after leaving the above scope we have no knowledge of any arguments or return
7890 // values from previous calls.
7891 expect_pending_htlcs_forwardable!(nodes[1]);
7892 let events = nodes[1].node.get_and_clear_pending_events();
7893 assert_eq!(events.len(), 1);
7895 Event::PaymentClaimable { ref purpose, .. } => {
7897 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7898 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7900 _ => panic!("expected PaymentPurpose::InvoicePayment")
7903 _ => panic!("Unexpected event"),
7908 #[allow(deprecated)]
7909 fn test_secret_timeout() {
7910 // Simple test of payment secret storage time outs. After
7911 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7912 let chanmon_cfgs = create_chanmon_cfgs(2);
7913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7917 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7919 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
7921 // We should fail to register the same payment hash twice, at least until we've connected a
7922 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
7923 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7924 assert_eq!(err, "Duplicate payment hash");
7925 } else { panic!(); }
7927 let node_1_blocks = nodes[1].blocks.lock().unwrap();
7929 header: BlockHeader {
7931 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
7932 merkle_root: TxMerkleNode::all_zeros(),
7933 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
7937 connect_block(&nodes[1], &block);
7938 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7939 assert_eq!(err, "Duplicate payment hash");
7940 } else { panic!(); }
7942 // If we then connect the second block, we should be able to register the same payment hash
7943 // again (this time getting a new payment secret).
7944 block.header.prev_blockhash = block.header.block_hash();
7945 block.header.time += 1;
7946 connect_block(&nodes[1], &block);
7947 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
7948 assert_ne!(payment_secret_1, our_payment_secret);
7951 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7952 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
7953 check_added_monitors!(nodes[0], 1);
7954 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7955 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7956 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7957 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7959 // Note that after leaving the above scope we have no knowledge of any arguments or return
7960 // values from previous calls.
7961 expect_pending_htlcs_forwardable!(nodes[1]);
7962 let events = nodes[1].node.get_and_clear_pending_events();
7963 assert_eq!(events.len(), 1);
7965 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
7966 assert!(payment_preimage.is_none());
7967 assert_eq!(payment_secret, our_payment_secret);
7968 // We don't actually have the payment preimage with which to claim this payment!
7970 _ => panic!("Unexpected event"),
7975 fn test_bad_secret_hash() {
7976 // Simple test of unregistered payment hash/invalid payment secret handling
7977 let chanmon_cfgs = create_chanmon_cfgs(2);
7978 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7979 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7980 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7982 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7984 let random_payment_hash = PaymentHash([42; 32]);
7985 let random_payment_secret = PaymentSecret([43; 32]);
7986 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
7987 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7989 // All the below cases should end up being handled exactly identically, so we macro the
7990 // resulting events.
7991 macro_rules! handle_unknown_invalid_payment_data {
7992 ($payment_hash: expr) => {
7993 check_added_monitors!(nodes[0], 1);
7994 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7995 let payment_event = SendEvent::from_event(events.pop().unwrap());
7996 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7997 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7999 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8000 // again to process the pending backwards-failure of the HTLC
8001 expect_pending_htlcs_forwardable!(nodes[1]);
8002 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8003 check_added_monitors!(nodes[1], 1);
8005 // We should fail the payment back
8006 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8007 match events.pop().unwrap() {
8008 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8009 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8010 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8012 _ => panic!("Unexpected event"),
8017 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8018 // Error data is the HTLC value (100,000) and current block height
8019 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8021 // Send a payment with the right payment hash but the wrong payment secret
8022 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8023 handle_unknown_invalid_payment_data!(our_payment_hash);
8024 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8026 // Send a payment with a random payment hash, but the right payment secret
8027 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8028 handle_unknown_invalid_payment_data!(random_payment_hash);
8029 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8031 // Send a payment with a random payment hash and random payment secret
8032 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8033 handle_unknown_invalid_payment_data!(random_payment_hash);
8034 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8038 fn test_update_err_monitor_lockdown() {
8039 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8040 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8041 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8044 // This scenario may happen in a watchtower setup, where watchtower process a block height
8045 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8046 // commitment at same time.
8048 let chanmon_cfgs = create_chanmon_cfgs(2);
8049 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8050 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8051 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8053 // Create some initial channel
8054 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8055 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8057 // Rebalance the network to generate htlc in the two directions
8058 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8060 // Route a HTLC from node 0 to node 1 (but don't settle)
8061 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8063 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8064 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8065 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8066 let persister = test_utils::TestPersister::new();
8068 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8069 let mut w = test_utils::TestVecWriter(Vec::new());
8070 monitor.write(&mut w).unwrap();
8071 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8072 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8073 assert!(new_monitor == *monitor);
8074 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);
8075 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8078 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8079 let block = Block { header, txdata: vec![] };
8080 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8081 // transaction lock time requirements here.
8082 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8083 watchtower.chain_monitor.block_connected(&block, 200);
8085 // Try to update ChannelMonitor
8086 nodes[1].node.claim_funds(preimage);
8087 check_added_monitors!(nodes[1], 1);
8088 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8090 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8091 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8092 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8093 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8094 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8095 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8096 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8097 } else { assert!(false); }
8098 } else { assert!(false); };
8099 // Our local monitor is in-sync and hasn't processed yet timeout
8100 check_added_monitors!(nodes[0], 1);
8101 let events = nodes[0].node.get_and_clear_pending_events();
8102 assert_eq!(events.len(), 1);
8106 fn test_concurrent_monitor_claim() {
8107 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8108 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8109 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8110 // state N+1 confirms. Alice claims output from state N+1.
8112 let chanmon_cfgs = create_chanmon_cfgs(2);
8113 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8114 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8115 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8117 // Create some initial channel
8118 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8119 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8121 // Rebalance the network to generate htlc in the two directions
8122 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8124 // Route a HTLC from node 0 to node 1 (but don't settle)
8125 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8127 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8128 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8129 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8130 let persister = test_utils::TestPersister::new();
8131 let watchtower_alice = {
8132 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8133 let mut w = test_utils::TestVecWriter(Vec::new());
8134 monitor.write(&mut w).unwrap();
8135 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8136 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8137 assert!(new_monitor == *monitor);
8138 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);
8139 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8142 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8143 let block = Block { header, txdata: vec![] };
8144 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8145 // transaction lock time requirements here.
8146 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8147 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8149 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8151 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8152 assert_eq!(txn.len(), 2);
8156 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8157 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8158 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8159 let persister = test_utils::TestPersister::new();
8160 let watchtower_bob = {
8161 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8162 let mut w = test_utils::TestVecWriter(Vec::new());
8163 monitor.write(&mut w).unwrap();
8164 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8165 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8166 assert!(new_monitor == *monitor);
8167 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);
8168 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8171 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8172 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8174 // Route another payment to generate another update with still previous HTLC pending
8175 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8177 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8179 check_added_monitors!(nodes[1], 1);
8181 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8182 assert_eq!(updates.update_add_htlcs.len(), 1);
8183 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8184 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8185 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8186 // Watchtower Alice should already have seen the block and reject the update
8187 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8188 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8189 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8190 } else { assert!(false); }
8191 } else { assert!(false); };
8192 // Our local monitor is in-sync and hasn't processed yet timeout
8193 check_added_monitors!(nodes[0], 1);
8195 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8196 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8197 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8199 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8202 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8203 assert_eq!(txn.len(), 2);
8204 bob_state_y = txn[0].clone();
8208 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8209 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8210 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![bob_state_y.clone()] }, CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8212 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8213 assert_eq!(htlc_txn.len(), 1);
8214 check_spends!(htlc_txn[0], bob_state_y);
8219 fn test_pre_lockin_no_chan_closed_update() {
8220 // Test that if a peer closes a channel in response to a funding_created message we don't
8221 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8224 // Doing so would imply a channel monitor update before the initial channel monitor
8225 // registration, violating our API guarantees.
8227 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8228 // then opening a second channel with the same funding output as the first (which is not
8229 // rejected because the first channel does not exist in the ChannelManager) and closing it
8230 // before receiving funding_signed.
8231 let chanmon_cfgs = create_chanmon_cfgs(2);
8232 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8233 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8234 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8236 // Create an initial channel
8237 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8238 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8239 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8240 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8241 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8243 // Move the first channel through the funding flow...
8244 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8246 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8247 check_added_monitors!(nodes[0], 0);
8249 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8250 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8251 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8252 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8253 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8257 fn test_htlc_no_detection() {
8258 // This test is a mutation to underscore the detection logic bug we had
8259 // before #653. HTLC value routed is above the remaining balance, thus
8260 // inverting HTLC and `to_remote` output. HTLC will come second and
8261 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8262 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8263 // outputs order detection for correct spending children filtring.
8265 let chanmon_cfgs = create_chanmon_cfgs(2);
8266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8268 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8270 // Create some initial channels
8271 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8273 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8274 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8275 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8276 assert_eq!(local_txn[0].input.len(), 1);
8277 assert_eq!(local_txn[0].output.len(), 3);
8278 check_spends!(local_txn[0], chan_1.3);
8280 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8281 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8282 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8283 // We deliberately connect the local tx twice as this should provoke a failure calling
8284 // this test before #653 fix.
8285 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &Block { header, txdata: vec![local_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
8286 check_closed_broadcast!(nodes[0], true);
8287 check_added_monitors!(nodes[0], 1);
8288 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8289 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8291 let htlc_timeout = {
8292 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8293 assert_eq!(node_txn.len(), 1);
8294 assert_eq!(node_txn[0].input.len(), 1);
8295 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8296 check_spends!(node_txn[0], local_txn[0]);
8300 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8301 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8302 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8303 expect_payment_failed!(nodes[0], our_payment_hash, false);
8306 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8307 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8308 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8309 // Carol, Alice would be the upstream node, and Carol the downstream.)
8311 // Steps of the test:
8312 // 1) Alice sends a HTLC to Carol through Bob.
8313 // 2) Carol doesn't settle the HTLC.
8314 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8315 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8316 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8317 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8318 // 5) Carol release the preimage to Bob off-chain.
8319 // 6) Bob claims the offered output on the broadcasted commitment.
8320 let chanmon_cfgs = create_chanmon_cfgs(3);
8321 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8322 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8323 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8325 // Create some initial channels
8326 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8327 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8329 // Steps (1) and (2):
8330 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8331 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8333 // Check that Alice's commitment transaction now contains an output for this HTLC.
8334 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8335 check_spends!(alice_txn[0], chan_ab.3);
8336 assert_eq!(alice_txn[0].output.len(), 2);
8337 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8338 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8339 assert_eq!(alice_txn.len(), 2);
8341 // Steps (3) and (4):
8342 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8343 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8344 let mut force_closing_node = 0; // Alice force-closes
8345 let mut counterparty_node = 1; // Bob if Alice force-closes
8348 if !broadcast_alice {
8349 force_closing_node = 1;
8350 counterparty_node = 0;
8352 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8353 check_closed_broadcast!(nodes[force_closing_node], true);
8354 check_added_monitors!(nodes[force_closing_node], 1);
8355 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8356 if go_onchain_before_fulfill {
8357 let txn_to_broadcast = match broadcast_alice {
8358 true => alice_txn.clone(),
8359 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8361 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8362 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8363 if broadcast_alice {
8364 check_closed_broadcast!(nodes[1], true);
8365 check_added_monitors!(nodes[1], 1);
8366 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8371 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8372 // process of removing the HTLC from their commitment transactions.
8373 nodes[2].node.claim_funds(payment_preimage);
8374 check_added_monitors!(nodes[2], 1);
8375 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8377 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8378 assert!(carol_updates.update_add_htlcs.is_empty());
8379 assert!(carol_updates.update_fail_htlcs.is_empty());
8380 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8381 assert!(carol_updates.update_fee.is_none());
8382 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8384 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8385 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8386 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8387 if !go_onchain_before_fulfill && broadcast_alice {
8388 let events = nodes[1].node.get_and_clear_pending_msg_events();
8389 assert_eq!(events.len(), 1);
8391 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8392 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8394 _ => panic!("Unexpected event"),
8397 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8398 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8399 // Carol<->Bob's updated commitment transaction info.
8400 check_added_monitors!(nodes[1], 2);
8402 let events = nodes[1].node.get_and_clear_pending_msg_events();
8403 assert_eq!(events.len(), 2);
8404 let bob_revocation = match events[0] {
8405 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8406 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8409 _ => panic!("Unexpected event"),
8411 let bob_updates = match events[1] {
8412 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8413 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8416 _ => panic!("Unexpected event"),
8419 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8420 check_added_monitors!(nodes[2], 1);
8421 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8422 check_added_monitors!(nodes[2], 1);
8424 let events = nodes[2].node.get_and_clear_pending_msg_events();
8425 assert_eq!(events.len(), 1);
8426 let carol_revocation = match events[0] {
8427 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8428 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8431 _ => panic!("Unexpected event"),
8433 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8434 check_added_monitors!(nodes[1], 1);
8436 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8437 // here's where we put said channel's commitment tx on-chain.
8438 let mut txn_to_broadcast = alice_txn.clone();
8439 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8440 if !go_onchain_before_fulfill {
8441 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8442 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8443 // If Bob was the one to force-close, he will have already passed these checks earlier.
8444 if broadcast_alice {
8445 check_closed_broadcast!(nodes[1], true);
8446 check_added_monitors!(nodes[1], 1);
8447 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8449 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8450 if broadcast_alice {
8451 assert_eq!(bob_txn.len(), 1);
8452 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8454 assert_eq!(bob_txn.len(), 2);
8455 check_spends!(bob_txn[0], chan_ab.3);
8460 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8461 // broadcasted commitment transaction.
8463 let script_weight = match broadcast_alice {
8464 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8465 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8467 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8468 // Bob force-closed and broadcasts the commitment transaction along with a
8469 // HTLC-output-claiming transaction.
8470 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8471 if broadcast_alice {
8472 assert_eq!(bob_txn.len(), 1);
8473 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8474 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8476 assert_eq!(bob_txn.len(), 2);
8477 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8478 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8484 fn test_onchain_htlc_settlement_after_close() {
8485 do_test_onchain_htlc_settlement_after_close(true, true);
8486 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8487 do_test_onchain_htlc_settlement_after_close(true, false);
8488 do_test_onchain_htlc_settlement_after_close(false, false);
8492 fn test_duplicate_chan_id() {
8493 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8494 // already open we reject it and keep the old channel.
8496 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8497 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8498 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8499 // updating logic for the existing channel.
8500 let chanmon_cfgs = create_chanmon_cfgs(2);
8501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8503 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8505 // Create an initial channel
8506 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8507 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8508 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8509 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8511 // Try to create a second channel with the same temporary_channel_id as the first and check
8512 // that it is rejected.
8513 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8515 let events = nodes[1].node.get_and_clear_pending_msg_events();
8516 assert_eq!(events.len(), 1);
8518 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8519 // Technically, at this point, nodes[1] would be justified in thinking both the
8520 // first (valid) and second (invalid) channels are closed, given they both have
8521 // the same non-temporary channel_id. However, currently we do not, so we just
8522 // move forward with it.
8523 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8524 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8526 _ => panic!("Unexpected event"),
8530 // Move the first channel through the funding flow...
8531 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8533 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8534 check_added_monitors!(nodes[0], 0);
8536 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8537 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8539 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8540 assert_eq!(added_monitors.len(), 1);
8541 assert_eq!(added_monitors[0].0, funding_output);
8542 added_monitors.clear();
8544 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8546 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8547 let channel_id = funding_outpoint.to_channel_id();
8549 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8552 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8553 // Technically this is allowed by the spec, but we don't support it and there's little reason
8554 // to. Still, it shouldn't cause any other issues.
8555 open_chan_msg.temporary_channel_id = channel_id;
8556 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8558 let events = nodes[1].node.get_and_clear_pending_msg_events();
8559 assert_eq!(events.len(), 1);
8561 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8562 // Technically, at this point, nodes[1] would be justified in thinking both
8563 // channels are closed, but currently we do not, so we just move forward with it.
8564 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8565 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8567 _ => panic!("Unexpected event"),
8571 // Now try to create a second channel which has a duplicate funding output.
8572 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8573 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8574 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
8575 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8576 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8578 let funding_created = {
8579 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8580 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8581 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8582 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8583 // channelmanager in a possibly nonsense state instead).
8584 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8585 let logger = test_utils::TestLogger::new();
8586 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8588 check_added_monitors!(nodes[0], 0);
8589 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8590 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8591 // still needs to be cleared here.
8592 check_added_monitors!(nodes[1], 1);
8594 // ...still, nodes[1] will reject the duplicate channel.
8596 let events = nodes[1].node.get_and_clear_pending_msg_events();
8597 assert_eq!(events.len(), 1);
8599 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8600 // Technically, at this point, nodes[1] would be justified in thinking both
8601 // channels are closed, but currently we do not, so we just move forward with it.
8602 assert_eq!(msg.channel_id, channel_id);
8603 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8605 _ => panic!("Unexpected event"),
8609 // finally, finish creating the original channel and send a payment over it to make sure
8610 // everything is functional.
8611 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8613 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8614 assert_eq!(added_monitors.len(), 1);
8615 assert_eq!(added_monitors[0].0, funding_output);
8616 added_monitors.clear();
8619 let events_4 = nodes[0].node.get_and_clear_pending_events();
8620 assert_eq!(events_4.len(), 0);
8621 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8622 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8624 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8625 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8626 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8628 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8632 fn test_error_chans_closed() {
8633 // Test that we properly handle error messages, closing appropriate channels.
8635 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8636 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8637 // we can test various edge cases around it to ensure we don't regress.
8638 let chanmon_cfgs = create_chanmon_cfgs(3);
8639 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8640 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8641 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8643 // Create some initial channels
8644 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8645 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8646 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8648 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8649 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8650 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8652 // Closing a channel from a different peer has no effect
8653 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8654 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8656 // Closing one channel doesn't impact others
8657 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8658 check_added_monitors!(nodes[0], 1);
8659 check_closed_broadcast!(nodes[0], false);
8660 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8661 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8662 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8663 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);
8664 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);
8666 // A null channel ID should close all channels
8667 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8668 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8669 check_added_monitors!(nodes[0], 2);
8670 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8671 let events = nodes[0].node.get_and_clear_pending_msg_events();
8672 assert_eq!(events.len(), 2);
8674 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8675 assert_eq!(msg.contents.flags & 2, 2);
8677 _ => panic!("Unexpected event"),
8680 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8681 assert_eq!(msg.contents.flags & 2, 2);
8683 _ => panic!("Unexpected event"),
8685 // Note that at this point users of a standard PeerHandler will end up calling
8686 // peer_disconnected with no_connection_possible set to false, duplicating the
8687 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8688 // users with their own peer handling logic. We duplicate the call here, however.
8689 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8690 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8692 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8693 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8694 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8698 fn test_invalid_funding_tx() {
8699 // Test that we properly handle invalid funding transactions sent to us from a peer.
8701 // Previously, all other major lightning implementations had failed to properly sanitize
8702 // funding transactions from their counterparties, leading to a multi-implementation critical
8703 // security vulnerability (though we always sanitized properly, we've previously had
8704 // un-released crashes in the sanitization process).
8706 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8707 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8708 // gave up on it. We test this here by generating such a transaction.
8709 let chanmon_cfgs = create_chanmon_cfgs(2);
8710 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8711 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8712 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8714 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8715 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
8716 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8718 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8720 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8721 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8722 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8724 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8725 let wit_program_script: Script = wit_program.into();
8726 for output in tx.output.iter_mut() {
8727 // Make the confirmed funding transaction have a bogus script_pubkey
8728 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8731 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8732 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()));
8733 check_added_monitors!(nodes[1], 1);
8735 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()));
8736 check_added_monitors!(nodes[0], 1);
8738 let events_1 = nodes[0].node.get_and_clear_pending_events();
8739 assert_eq!(events_1.len(), 0);
8741 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8742 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8743 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8745 let expected_err = "funding tx had wrong script/value or output index";
8746 confirm_transaction_at(&nodes[1], &tx, 1);
8747 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8748 check_added_monitors!(nodes[1], 1);
8749 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8750 assert_eq!(events_2.len(), 1);
8751 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8752 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8753 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8754 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8755 } else { panic!(); }
8756 } else { panic!(); }
8757 assert_eq!(nodes[1].node.list_channels().len(), 0);
8759 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8760 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8761 // as its not 32 bytes long.
8762 let mut spend_tx = Transaction {
8763 version: 2i32, lock_time: PackedLockTime::ZERO,
8764 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8765 previous_output: BitcoinOutPoint {
8769 script_sig: Script::new(),
8770 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8771 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8773 output: vec![TxOut {
8775 script_pubkey: Script::new(),
8778 check_spends!(spend_tx, tx);
8779 mine_transaction(&nodes[1], &spend_tx);
8782 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8783 // In the first version of the chain::Confirm interface, after a refactor was made to not
8784 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8785 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8786 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8787 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8788 // spending transaction until height N+1 (or greater). This was due to the way
8789 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8790 // spending transaction at the height the input transaction was confirmed at, not whether we
8791 // should broadcast a spending transaction at the current height.
8792 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8793 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8794 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8795 // until we learned about an additional block.
8797 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8798 // aren't broadcasting transactions too early (ie not broadcasting them at all).
8799 let chanmon_cfgs = create_chanmon_cfgs(3);
8800 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8801 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8802 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8803 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8805 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8806 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8807 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8808 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8809 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8811 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8812 check_closed_broadcast!(nodes[1], true);
8813 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8814 check_added_monitors!(nodes[1], 1);
8815 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8816 assert_eq!(node_txn.len(), 1);
8818 let conf_height = nodes[1].best_block_info().1;
8819 if !test_height_before_timelock {
8820 connect_blocks(&nodes[1], 24 * 6);
8822 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8823 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8824 if test_height_before_timelock {
8825 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8826 // generate any events or broadcast any transactions
8827 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8828 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8830 // We should broadcast an HTLC transaction spending our funding transaction first
8831 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8832 assert_eq!(spending_txn.len(), 2);
8833 assert_eq!(spending_txn[0], node_txn[0]);
8834 check_spends!(spending_txn[1], node_txn[0]);
8835 // We should also generate a SpendableOutputs event with the to_self output (as its
8837 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8838 assert_eq!(descriptor_spend_txn.len(), 1);
8840 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8841 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8842 // additional block built on top of the current chain.
8843 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8844 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8845 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 }]);
8846 check_added_monitors!(nodes[1], 1);
8848 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8849 assert!(updates.update_add_htlcs.is_empty());
8850 assert!(updates.update_fulfill_htlcs.is_empty());
8851 assert_eq!(updates.update_fail_htlcs.len(), 1);
8852 assert!(updates.update_fail_malformed_htlcs.is_empty());
8853 assert!(updates.update_fee.is_none());
8854 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8855 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8856 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
8861 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
8862 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
8863 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
8866 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
8867 let chanmon_cfgs = create_chanmon_cfgs(2);
8868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8870 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8872 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8874 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
8875 .with_features(channelmanager::provided_invoice_features());
8876 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
8878 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
8881 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8882 check_added_monitors!(nodes[0], 1);
8883 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8884 assert_eq!(events.len(), 1);
8885 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8886 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8887 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8889 expect_pending_htlcs_forwardable!(nodes[1]);
8890 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
8893 // Note that we use a different PaymentId here to allow us to duplicativly pay
8894 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
8895 check_added_monitors!(nodes[0], 1);
8896 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8897 assert_eq!(events.len(), 1);
8898 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8899 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8900 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8901 // At this point, nodes[1] would notice it has too much value for the payment. It will
8902 // assume the second is a privacy attack (no longer particularly relevant
8903 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
8904 // the first HTLC delivered above.
8907 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
8908 nodes[1].node.process_pending_htlc_forwards();
8910 if test_for_second_fail_panic {
8911 // Now we go fail back the first HTLC from the user end.
8912 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
8914 let expected_destinations = vec![
8915 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8916 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8918 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
8919 nodes[1].node.process_pending_htlc_forwards();
8921 check_added_monitors!(nodes[1], 1);
8922 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8923 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
8925 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
8926 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
8927 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
8929 let failure_events = nodes[0].node.get_and_clear_pending_events();
8930 assert_eq!(failure_events.len(), 2);
8931 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
8932 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
8934 // Let the second HTLC fail and claim the first
8935 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
8936 nodes[1].node.process_pending_htlc_forwards();
8938 check_added_monitors!(nodes[1], 1);
8939 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8940 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
8941 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
8943 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
8945 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8950 fn test_dup_htlc_second_fail_panic() {
8951 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
8952 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
8953 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
8954 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
8955 do_test_dup_htlc_second_rejected(true);
8959 fn test_dup_htlc_second_rejected() {
8960 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
8961 // simply reject the second HTLC but are still able to claim the first HTLC.
8962 do_test_dup_htlc_second_rejected(false);
8966 fn test_inconsistent_mpp_params() {
8967 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
8968 // such HTLC and allow the second to stay.
8969 let chanmon_cfgs = create_chanmon_cfgs(4);
8970 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8971 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8972 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8974 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8975 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8976 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8977 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8979 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
8980 .with_features(channelmanager::provided_invoice_features());
8981 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
8982 assert_eq!(route.paths.len(), 2);
8983 route.paths.sort_by(|path_a, _| {
8984 // Sort the path so that the path through nodes[1] comes first
8985 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
8986 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
8988 let payment_params_opt = Some(payment_params);
8990 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8992 let cur_height = nodes[0].best_block_info().1;
8993 let payment_id = PaymentId([42; 32]);
8995 let session_privs = {
8996 // We create a fake route here so that we start with three pending HTLCs, which we'll
8997 // ultimately have, just not right away.
8998 let mut dup_route = route.clone();
8999 dup_route.paths.push(route.paths[1].clone());
9000 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9003 nodes[0].node.send_payment_along_path(&route.paths[0], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9004 check_added_monitors!(nodes[0], 1);
9006 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9007 assert_eq!(events.len(), 1);
9008 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9010 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9013 nodes[0].node.send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9014 check_added_monitors!(nodes[0], 1);
9016 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9017 assert_eq!(events.len(), 1);
9018 let payment_event = SendEvent::from_event(events.pop().unwrap());
9020 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9021 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9023 expect_pending_htlcs_forwardable!(nodes[2]);
9024 check_added_monitors!(nodes[2], 1);
9026 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9027 assert_eq!(events.len(), 1);
9028 let payment_event = SendEvent::from_event(events.pop().unwrap());
9030 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9031 check_added_monitors!(nodes[3], 0);
9032 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9034 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9035 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9036 // post-payment_secrets) and fail back the new HTLC.
9038 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9039 nodes[3].node.process_pending_htlc_forwards();
9040 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9041 nodes[3].node.process_pending_htlc_forwards();
9043 check_added_monitors!(nodes[3], 1);
9045 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9046 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9047 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9049 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 }]);
9050 check_added_monitors!(nodes[2], 1);
9052 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9053 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9054 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9056 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9058 nodes[0].node.send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[2]).unwrap();
9059 check_added_monitors!(nodes[0], 1);
9061 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9062 assert_eq!(events.len(), 1);
9063 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9065 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9069 fn test_keysend_payments_to_public_node() {
9070 let chanmon_cfgs = create_chanmon_cfgs(2);
9071 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9072 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9073 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9075 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9076 let network_graph = nodes[0].network_graph.clone();
9077 let payer_pubkey = nodes[0].node.get_our_node_id();
9078 let payee_pubkey = nodes[1].node.get_our_node_id();
9079 let route_params = RouteParameters {
9080 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9081 final_value_msat: 10000,
9082 final_cltv_expiry_delta: 40,
9084 let scorer = test_utils::TestScorer::with_penalty(0);
9085 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9086 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9088 let test_preimage = PaymentPreimage([42; 32]);
9089 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9090 check_added_monitors!(nodes[0], 1);
9091 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9092 assert_eq!(events.len(), 1);
9093 let event = events.pop().unwrap();
9094 let path = vec![&nodes[1]];
9095 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9096 claim_payment(&nodes[0], &path, test_preimage);
9100 fn test_keysend_payments_to_private_node() {
9101 let chanmon_cfgs = create_chanmon_cfgs(2);
9102 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9103 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9104 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9106 let payer_pubkey = nodes[0].node.get_our_node_id();
9107 let payee_pubkey = nodes[1].node.get_our_node_id();
9108 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9109 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9111 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9112 let route_params = RouteParameters {
9113 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9114 final_value_msat: 10000,
9115 final_cltv_expiry_delta: 40,
9117 let network_graph = nodes[0].network_graph.clone();
9118 let first_hops = nodes[0].node.list_usable_channels();
9119 let scorer = test_utils::TestScorer::with_penalty(0);
9120 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9121 let route = find_route(
9122 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9123 nodes[0].logger, &scorer, &random_seed_bytes
9126 let test_preimage = PaymentPreimage([42; 32]);
9127 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9128 check_added_monitors!(nodes[0], 1);
9129 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9130 assert_eq!(events.len(), 1);
9131 let event = events.pop().unwrap();
9132 let path = vec![&nodes[1]];
9133 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9134 claim_payment(&nodes[0], &path, test_preimage);
9138 fn test_double_partial_claim() {
9139 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9140 // time out, the sender resends only some of the MPP parts, then the user processes the
9141 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9143 let chanmon_cfgs = create_chanmon_cfgs(4);
9144 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9145 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9146 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9148 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9149 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9150 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9151 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9153 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9154 assert_eq!(route.paths.len(), 2);
9155 route.paths.sort_by(|path_a, _| {
9156 // Sort the path so that the path through nodes[1] comes first
9157 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9158 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9161 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9162 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9163 // amount of time to respond to.
9165 // Connect some blocks to time out the payment
9166 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9167 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9169 let failed_destinations = vec![
9170 HTLCDestination::FailedPayment { payment_hash },
9171 HTLCDestination::FailedPayment { payment_hash },
9173 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9175 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9177 // nodes[1] now retries one of the two paths...
9178 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9179 check_added_monitors!(nodes[0], 2);
9181 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9182 assert_eq!(events.len(), 2);
9183 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9185 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9186 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9187 nodes[3].node.claim_funds(payment_preimage);
9188 check_added_monitors!(nodes[3], 0);
9189 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9192 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9193 #[derive(Clone, Copy, PartialEq)]
9194 enum ExposureEvent {
9195 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9197 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9199 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9200 AtUpdateFeeOutbound,
9203 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9204 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9207 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9208 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9209 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9210 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9211 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9212 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9213 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9214 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9216 let chanmon_cfgs = create_chanmon_cfgs(2);
9217 let mut config = test_default_channel_config();
9218 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9219 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9220 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9221 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9223 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9224 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9225 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9226 open_channel.max_accepted_htlcs = 60;
9228 open_channel.dust_limit_satoshis = 546;
9230 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
9231 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9232 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
9234 let opt_anchors = false;
9236 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9239 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9240 chan.holder_dust_limit_satoshis = 546;
9244 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9245 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()));
9246 check_added_monitors!(nodes[1], 1);
9248 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()));
9249 check_added_monitors!(nodes[0], 1);
9251 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9252 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9253 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9255 let dust_buffer_feerate = {
9256 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9257 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9258 chan.get_dust_buffer_feerate(None) as u64
9260 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;
9261 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9263 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;
9264 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9266 let dust_htlc_on_counterparty_tx: u64 = 25;
9267 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9270 if dust_outbound_balance {
9271 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9272 // Outbound dust balance: 4372 sats
9273 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9274 for i in 0..dust_outbound_htlc_on_holder_tx {
9275 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9276 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9279 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9280 // Inbound dust balance: 4372 sats
9281 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9282 for _ in 0..dust_inbound_htlc_on_holder_tx {
9283 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9287 if dust_outbound_balance {
9288 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9289 // Outbound dust balance: 5000 sats
9290 for i in 0..dust_htlc_on_counterparty_tx {
9291 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9292 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9295 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9296 // Inbound dust balance: 5000 sats
9297 for _ in 0..dust_htlc_on_counterparty_tx {
9298 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9303 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9304 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9305 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9306 let mut config = UserConfig::default();
9307 // With default dust exposure: 5000 sats
9309 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9310 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9311 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9313 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9315 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9316 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 });
9317 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9318 check_added_monitors!(nodes[1], 1);
9319 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9320 assert_eq!(events.len(), 1);
9321 let payment_event = SendEvent::from_event(events.remove(0));
9322 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9323 // With default dust exposure: 5000 sats
9325 // Outbound dust balance: 6399 sats
9326 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9327 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9328 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);
9330 // Outbound dust balance: 5200 sats
9331 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
9333 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9334 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9335 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9337 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9338 *feerate_lock = *feerate_lock * 10;
9340 nodes[0].node.timer_tick_occurred();
9341 check_added_monitors!(nodes[0], 1);
9342 nodes[0].logger.assert_log_contains("lightning::ln::channel".to_string(), "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure".to_string(), 1);
9345 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9346 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9347 added_monitors.clear();
9351 fn test_max_dust_htlc_exposure() {
9352 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9353 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9354 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9355 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9356 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9357 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9358 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9359 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9360 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9361 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9362 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9363 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9367 fn test_non_final_funding_tx() {
9368 let chanmon_cfgs = create_chanmon_cfgs(2);
9369 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9370 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9371 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9373 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9374 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9375 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
9376 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9377 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
9379 let best_height = nodes[0].node.best_block.read().unwrap().height();
9381 let chan_id = *nodes[0].network_chan_count.borrow();
9382 let events = nodes[0].node.get_and_clear_pending_events();
9383 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9384 assert_eq!(events.len(), 1);
9385 let mut tx = match events[0] {
9386 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9387 // Timelock the transaction _beyond_ the best client height + 2.
9388 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9389 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9392 _ => panic!("Unexpected event"),
9394 // Transaction should fail as it's evaluated as non-final for propagation.
9395 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9396 Err(APIError::APIMisuseError { err }) => {
9397 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9402 // However, transaction should be accepted if it's in a +2 headroom from best block.
9403 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9404 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9405 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9409 fn accept_busted_but_better_fee() {
9410 // If a peer sends us a fee update that is too low, but higher than our previous channel
9411 // feerate, we should accept it. In the future we may want to consider closing the channel
9412 // later, but for now we only accept the update.
9413 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9415 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9416 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9418 create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9420 // Set nodes[1] to expect 5,000 sat/kW.
9422 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9423 *feerate_lock = 5000;
9426 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9428 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9429 *feerate_lock = 1000;
9431 nodes[0].node.timer_tick_occurred();
9432 check_added_monitors!(nodes[0], 1);
9434 let events = nodes[0].node.get_and_clear_pending_msg_events();
9435 assert_eq!(events.len(), 1);
9437 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9438 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9439 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9441 _ => panic!("Unexpected event"),
9444 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9447 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9448 *feerate_lock = 2000;
9450 nodes[0].node.timer_tick_occurred();
9451 check_added_monitors!(nodes[0], 1);
9453 let events = nodes[0].node.get_and_clear_pending_msg_events();
9454 assert_eq!(events.len(), 1);
9456 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9457 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9458 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9460 _ => panic!("Unexpected event"),
9463 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9466 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9467 *feerate_lock = 1000;
9469 nodes[0].node.timer_tick_occurred();
9470 check_added_monitors!(nodes[0], 1);
9472 let events = nodes[0].node.get_and_clear_pending_msg_events();
9473 assert_eq!(events.len(), 1);
9475 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9476 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9477 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9478 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9479 check_closed_broadcast!(nodes[1], true);
9480 check_added_monitors!(nodes[1], 1);
9482 _ => panic!("Unexpected event"),