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, 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::{byte_utils, 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::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).unwrap();
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::PaymentReceived { .. } => { },
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::PaymentReceived { 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(), 5);
1273 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1274 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1275 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1277 check_spends!(claim_txn[3], remote_txn[0]);
1278 check_spends!(claim_txn[4], remote_txn[0]);
1279 let preimage_tx = &claim_txn[0];
1280 let (preimage_bump_tx, timeout_tx) = if claim_txn[3].input[0].previous_output == preimage_tx.input[0].previous_output {
1281 (&claim_txn[3], &claim_txn[4])
1283 (&claim_txn[4], &claim_txn[3])
1286 assert_eq!(preimage_tx.input.len(), 1);
1287 assert_eq!(preimage_bump_tx.input.len(), 1);
1289 assert_eq!(preimage_tx.input.len(), 1);
1290 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1291 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1293 assert_eq!(timeout_tx.input.len(), 1);
1294 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1295 check_spends!(timeout_tx, remote_txn[0]);
1296 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1298 let events = nodes[0].node.get_and_clear_pending_msg_events();
1299 assert_eq!(events.len(), 3);
1302 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1303 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1304 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1305 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1307 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, .. } } => {
1308 assert!(update_add_htlcs.is_empty());
1309 assert!(update_fail_htlcs.is_empty());
1310 assert_eq!(update_fulfill_htlcs.len(), 1);
1311 assert!(update_fail_malformed_htlcs.is_empty());
1312 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1314 _ => panic!("Unexpected event"),
1320 fn test_basic_channel_reserve() {
1321 let chanmon_cfgs = create_chanmon_cfgs(2);
1322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1324 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1325 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1327 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1328 let channel_reserve = chan_stat.channel_reserve_msat;
1330 // The 2* and +1 are for the fee spike reserve.
1331 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1332 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1333 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1334 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1336 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1338 &APIError::ChannelUnavailable{ref err} =>
1339 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1340 _ => panic!("Unexpected error variant"),
1343 _ => panic!("Unexpected error variant"),
1345 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1346 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);
1348 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1352 fn test_fee_spike_violation_fails_htlc() {
1353 let chanmon_cfgs = create_chanmon_cfgs(2);
1354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1356 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1357 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1359 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1360 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1361 let secp_ctx = Secp256k1::new();
1362 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1364 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1366 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1367 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1368 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1369 let msg = msgs::UpdateAddHTLC {
1372 amount_msat: htlc_msat,
1373 payment_hash: payment_hash,
1374 cltv_expiry: htlc_cltv,
1375 onion_routing_packet: onion_packet,
1378 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1380 // Now manually create the commitment_signed message corresponding to the update_add
1381 // nodes[0] just sent. In the code for construction of this message, "local" refers
1382 // to the sender of the message, and "remote" refers to the receiver.
1384 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1386 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1388 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1389 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1390 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1391 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1392 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1393 let chan_signer = local_chan.get_signer();
1394 // Make the signer believe we validated another commitment, so we can release the secret
1395 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1397 let pubkeys = chan_signer.pubkeys();
1398 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1399 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1400 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1401 chan_signer.pubkeys().funding_pubkey)
1403 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1404 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1405 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1406 let chan_signer = remote_chan.get_signer();
1407 let pubkeys = chan_signer.pubkeys();
1408 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1409 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1410 chan_signer.pubkeys().funding_pubkey)
1413 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1414 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1415 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1417 // Build the remote commitment transaction so we can sign it, and then later use the
1418 // signature for the commitment_signed message.
1419 let local_chan_balance = 1313;
1421 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1423 amount_msat: 3460001,
1424 cltv_expiry: htlc_cltv,
1426 transaction_output_index: Some(1),
1429 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1432 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1433 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1434 let local_chan_signer = local_chan.get_signer();
1435 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1439 local_chan.opt_anchors(), local_funding, remote_funding,
1440 commit_tx_keys.clone(),
1442 &mut vec![(accepted_htlc_info, ())],
1443 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1445 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1448 let commit_signed_msg = msgs::CommitmentSigned {
1451 htlc_signatures: res.1
1454 // Send the commitment_signed message to the nodes[1].
1455 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1456 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1458 // Send the RAA to nodes[1].
1459 let raa_msg = msgs::RevokeAndACK {
1461 per_commitment_secret: local_secret,
1462 next_per_commitment_point: next_local_point
1464 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1466 let events = nodes[1].node.get_and_clear_pending_msg_events();
1467 assert_eq!(events.len(), 1);
1468 // Make sure the HTLC failed in the way we expect.
1470 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1471 assert_eq!(update_fail_htlcs.len(), 1);
1472 update_fail_htlcs[0].clone()
1474 _ => panic!("Unexpected event"),
1476 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1477 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1479 check_added_monitors!(nodes[1], 2);
1483 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1484 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1485 // Set the fee rate for the channel very high, to the point where the fundee
1486 // sending any above-dust amount would result in a channel reserve violation.
1487 // In this test we check that we would be prevented from sending an HTLC in
1489 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1492 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1493 let default_config = UserConfig::default();
1494 let opt_anchors = false;
1496 let mut push_amt = 100_000_000;
1497 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1499 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1501 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1503 // Sending exactly enough to hit the reserve amount should be accepted
1504 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1505 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1508 // However one more HTLC should be significantly over the reserve amount and fail.
1509 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1510 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 },
1511 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1512 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1513 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);
1517 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1518 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1519 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1522 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523 let default_config = UserConfig::default();
1524 let opt_anchors = false;
1526 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1527 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1528 // transaction fee with 0 HTLCs (183 sats)).
1529 let mut push_amt = 100_000_000;
1530 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1531 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1532 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1534 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1535 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1536 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1539 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1540 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1541 let secp_ctx = Secp256k1::new();
1542 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1543 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1544 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1545 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1546 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1547 let msg = msgs::UpdateAddHTLC {
1549 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1550 amount_msat: htlc_msat,
1551 payment_hash: payment_hash,
1552 cltv_expiry: htlc_cltv,
1553 onion_routing_packet: onion_packet,
1556 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1557 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1558 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);
1559 assert_eq!(nodes[0].node.list_channels().len(), 0);
1560 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1561 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1562 check_added_monitors!(nodes[0], 1);
1563 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() });
1567 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1568 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1569 // calculating our commitment transaction fee (this was previously broken).
1570 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1571 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1575 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1576 let default_config = UserConfig::default();
1577 let opt_anchors = false;
1579 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1580 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1581 // transaction fee with 0 HTLCs (183 sats)).
1582 let mut push_amt = 100_000_000;
1583 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1584 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1585 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1587 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1588 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1589 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1590 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1591 // commitment transaction fee.
1592 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1594 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1595 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1596 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1599 // One more than the dust amt should fail, however.
1600 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1601 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 },
1602 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1606 fn test_chan_init_feerate_unaffordability() {
1607 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1608 // channel reserve and feerate requirements.
1609 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1610 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1613 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1614 let default_config = UserConfig::default();
1615 let opt_anchors = false;
1617 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1619 let mut push_amt = 100_000_000;
1620 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1621 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1622 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1624 // During open, we don't have a "counterparty channel reserve" to check against, so that
1625 // requirement only comes into play on the open_channel handling side.
1626 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1627 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1628 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1629 open_channel_msg.push_msat += 1;
1630 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1632 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1633 assert_eq!(msg_events.len(), 1);
1634 match msg_events[0] {
1635 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1636 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1638 _ => panic!("Unexpected event"),
1643 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1644 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1645 // calculating our counterparty's commitment transaction fee (this was previously broken).
1646 let chanmon_cfgs = create_chanmon_cfgs(2);
1647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1649 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1650 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1652 let payment_amt = 46000; // Dust amount
1653 // In the previous code, these first four payments would succeed.
1654 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1655 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1656 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1657 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1659 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1660 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1667 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1668 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1669 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1674 let chanmon_cfgs = create_chanmon_cfgs(3);
1675 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1676 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1677 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1678 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1679 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1682 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1683 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1684 let feerate = get_feerate!(nodes[0], chan.2);
1685 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1687 // Add a 2* and +1 for the fee spike reserve.
1688 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1689 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;
1690 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1692 // Add a pending HTLC.
1693 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1694 let payment_event_1 = {
1695 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1696 check_added_monitors!(nodes[0], 1);
1698 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1699 assert_eq!(events.len(), 1);
1700 SendEvent::from_event(events.remove(0))
1702 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1704 // Attempt to trigger a channel reserve violation --> payment failure.
1705 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1706 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;
1707 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1708 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1710 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1711 let secp_ctx = Secp256k1::new();
1712 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1713 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1714 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1715 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1716 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1717 let msg = msgs::UpdateAddHTLC {
1720 amount_msat: htlc_msat + 1,
1721 payment_hash: our_payment_hash_1,
1722 cltv_expiry: htlc_cltv,
1723 onion_routing_packet: onion_packet,
1726 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1727 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1728 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1729 assert_eq!(nodes[1].node.list_channels().len(), 1);
1730 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1731 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1732 check_added_monitors!(nodes[1], 1);
1733 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1737 fn test_inbound_outbound_capacity_is_not_zero() {
1738 let chanmon_cfgs = create_chanmon_cfgs(2);
1739 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1740 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1741 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1742 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1743 let channels0 = node_chanmgrs[0].list_channels();
1744 let channels1 = node_chanmgrs[1].list_channels();
1745 let default_config = UserConfig::default();
1746 assert_eq!(channels0.len(), 1);
1747 assert_eq!(channels1.len(), 1);
1749 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1750 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1751 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1753 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1754 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1757 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1758 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1762 fn test_channel_reserve_holding_cell_htlcs() {
1763 let chanmon_cfgs = create_chanmon_cfgs(3);
1764 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1765 // When this test was written, the default base fee floated based on the HTLC count.
1766 // It is now fixed, so we simply set the fee to the expected value here.
1767 let mut config = test_default_channel_config();
1768 config.channel_config.forwarding_fee_base_msat = 239;
1769 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1770 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1771 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1772 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1774 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1775 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1777 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1778 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1780 macro_rules! expect_forward {
1782 let mut events = $node.node.get_and_clear_pending_msg_events();
1783 assert_eq!(events.len(), 1);
1784 check_added_monitors!($node, 1);
1785 let payment_event = SendEvent::from_event(events.remove(0));
1790 let feemsat = 239; // set above
1791 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1792 let feerate = get_feerate!(nodes[0], chan_1.2);
1793 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1795 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1797 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1799 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1800 .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1801 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);
1802 route.paths[0].last_mut().unwrap().fee_msat += 1;
1803 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1805 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 },
1806 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)));
1807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1808 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);
1811 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1812 // nodes[0]'s wealth
1814 let amt_msat = recv_value_0 + total_fee_msat;
1815 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1816 // Also, ensure that each payment has enough to be over the dust limit to
1817 // ensure it'll be included in each commit tx fee calculation.
1818 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1819 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1820 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1824 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1825 .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1826 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1827 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1828 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1830 let (stat01_, stat11_, stat12_, stat22_) = (
1831 get_channel_value_stat!(nodes[0], chan_1.2),
1832 get_channel_value_stat!(nodes[1], chan_1.2),
1833 get_channel_value_stat!(nodes[1], chan_2.2),
1834 get_channel_value_stat!(nodes[2], chan_2.2),
1837 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1838 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1839 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1840 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1841 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1844 // adding pending output.
1845 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1846 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1847 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1848 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1849 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1850 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1851 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1852 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1853 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1855 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1856 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1857 let amt_msat_1 = recv_value_1 + total_fee_msat;
1859 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);
1860 let payment_event_1 = {
1861 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1862 check_added_monitors!(nodes[0], 1);
1864 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1865 assert_eq!(events.len(), 1);
1866 SendEvent::from_event(events.remove(0))
1868 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1870 // channel reserve test with htlc pending output > 0
1871 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1873 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1874 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 },
1875 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1876 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1879 // split the rest to test holding cell
1880 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1881 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1882 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1883 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1885 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1886 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);
1889 // now see if they go through on both sides
1890 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);
1891 // but this will stuck in the holding cell
1892 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1893 check_added_monitors!(nodes[0], 0);
1894 let events = nodes[0].node.get_and_clear_pending_events();
1895 assert_eq!(events.len(), 0);
1897 // test with outbound holding cell amount > 0
1899 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1900 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 },
1901 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1902 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1903 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);
1906 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);
1907 // this will also stuck in the holding cell
1908 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1909 check_added_monitors!(nodes[0], 0);
1910 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1913 // flush the pending htlc
1914 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1915 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1916 check_added_monitors!(nodes[1], 1);
1918 // the pending htlc should be promoted to committed
1919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1920 check_added_monitors!(nodes[0], 1);
1921 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1923 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1924 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1925 // No commitment_signed so get_event_msg's assert(len == 1) passes
1926 check_added_monitors!(nodes[0], 1);
1928 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1929 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1930 check_added_monitors!(nodes[1], 1);
1932 expect_pending_htlcs_forwardable!(nodes[1]);
1934 let ref payment_event_11 = expect_forward!(nodes[1]);
1935 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1936 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1938 expect_pending_htlcs_forwardable!(nodes[2]);
1939 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1941 // flush the htlcs in the holding cell
1942 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1943 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1944 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1945 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1946 expect_pending_htlcs_forwardable!(nodes[1]);
1948 let ref payment_event_3 = expect_forward!(nodes[1]);
1949 assert_eq!(payment_event_3.msgs.len(), 2);
1950 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1951 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1953 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1954 expect_pending_htlcs_forwardable!(nodes[2]);
1956 let events = nodes[2].node.get_and_clear_pending_events();
1957 assert_eq!(events.len(), 2);
1959 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1960 assert_eq!(our_payment_hash_21, *payment_hash);
1961 assert_eq!(recv_value_21, amount_msat);
1963 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1964 assert!(payment_preimage.is_none());
1965 assert_eq!(our_payment_secret_21, *payment_secret);
1967 _ => panic!("expected PaymentPurpose::InvoicePayment")
1970 _ => panic!("Unexpected event"),
1973 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1974 assert_eq!(our_payment_hash_22, *payment_hash);
1975 assert_eq!(recv_value_22, amount_msat);
1977 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1978 assert!(payment_preimage.is_none());
1979 assert_eq!(our_payment_secret_22, *payment_secret);
1981 _ => panic!("expected PaymentPurpose::InvoicePayment")
1984 _ => panic!("Unexpected event"),
1987 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1988 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1989 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1991 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1992 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1993 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1995 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1996 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);
1997 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1998 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1999 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2001 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2002 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2006 fn channel_reserve_in_flight_removes() {
2007 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2008 // can send to its counterparty, but due to update ordering, the other side may not yet have
2009 // considered those HTLCs fully removed.
2010 // This tests that we don't count HTLCs which will not be included in the next remote
2011 // commitment transaction towards the reserve value (as it implies no commitment transaction
2012 // will be generated which violates the remote reserve value).
2013 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2015 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2016 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2017 // you only consider the value of the first HTLC, it may not),
2018 // * start routing a third HTLC from A to B,
2019 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2020 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2021 // * deliver the first fulfill from B
2022 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2024 // * deliver A's response CS and RAA.
2025 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2026 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2027 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2028 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2029 let chanmon_cfgs = create_chanmon_cfgs(2);
2030 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2031 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2032 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2033 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2035 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2036 // Route the first two HTLCs.
2037 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2038 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2039 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2041 // Start routing the third HTLC (this is just used to get everyone in the right state).
2042 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2044 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2045 check_added_monitors!(nodes[0], 1);
2046 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2047 assert_eq!(events.len(), 1);
2048 SendEvent::from_event(events.remove(0))
2051 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2052 // initial fulfill/CS.
2053 nodes[1].node.claim_funds(payment_preimage_1);
2054 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2055 check_added_monitors!(nodes[1], 1);
2056 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2058 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2059 // remove the second HTLC when we send the HTLC back from B to A.
2060 nodes[1].node.claim_funds(payment_preimage_2);
2061 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2062 check_added_monitors!(nodes[1], 1);
2063 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2065 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2066 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2067 check_added_monitors!(nodes[0], 1);
2068 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2069 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2071 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2072 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2073 check_added_monitors!(nodes[1], 1);
2074 // B is already AwaitingRAA, so cant generate a CS here
2075 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2077 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2078 check_added_monitors!(nodes[1], 1);
2079 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2081 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2082 check_added_monitors!(nodes[0], 1);
2083 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2085 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2086 check_added_monitors!(nodes[1], 1);
2087 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2089 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2090 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2091 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2092 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2093 // on-chain as necessary).
2094 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2095 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2096 check_added_monitors!(nodes[0], 1);
2097 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2098 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2100 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2101 check_added_monitors!(nodes[1], 1);
2102 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2104 expect_pending_htlcs_forwardable!(nodes[1]);
2105 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2107 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2108 // resolve the second HTLC from A's point of view.
2109 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2110 check_added_monitors!(nodes[0], 1);
2111 expect_payment_path_successful!(nodes[0]);
2112 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2114 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2115 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2116 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2118 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2119 check_added_monitors!(nodes[1], 1);
2120 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2121 assert_eq!(events.len(), 1);
2122 SendEvent::from_event(events.remove(0))
2125 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2126 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2127 check_added_monitors!(nodes[0], 1);
2128 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2130 // Now just resolve all the outstanding messages/HTLCs for completeness...
2132 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2133 check_added_monitors!(nodes[1], 1);
2134 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2136 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2137 check_added_monitors!(nodes[1], 1);
2139 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2140 check_added_monitors!(nodes[0], 1);
2141 expect_payment_path_successful!(nodes[0]);
2142 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2144 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2145 check_added_monitors!(nodes[1], 1);
2146 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2148 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2149 check_added_monitors!(nodes[0], 1);
2151 expect_pending_htlcs_forwardable!(nodes[0]);
2152 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2154 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2155 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2159 fn channel_monitor_network_test() {
2160 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2161 // tests that ChannelMonitor is able to recover from various states.
2162 let chanmon_cfgs = create_chanmon_cfgs(5);
2163 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2164 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2165 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2167 // Create some initial channels
2168 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2169 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2170 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2171 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2173 // Make sure all nodes are at the same starting height
2174 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2175 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2176 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2177 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2178 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2180 // Rebalance the network a bit by relaying one payment through all the channels...
2181 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
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);
2186 // Simple case with no pending HTLCs:
2187 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2188 check_added_monitors!(nodes[1], 1);
2189 check_closed_broadcast!(nodes[1], true);
2191 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2192 assert_eq!(node_txn.len(), 1);
2193 mine_transaction(&nodes[0], &node_txn[0]);
2194 check_added_monitors!(nodes[0], 1);
2195 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2197 check_closed_broadcast!(nodes[0], true);
2198 assert_eq!(nodes[0].node.list_channels().len(), 0);
2199 assert_eq!(nodes[1].node.list_channels().len(), 1);
2200 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2201 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2203 // One pending HTLC is discarded by the force-close:
2204 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2206 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2207 // broadcasted until we reach the timelock time).
2208 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2209 check_closed_broadcast!(nodes[1], true);
2210 check_added_monitors!(nodes[1], 1);
2212 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2213 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2214 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2215 mine_transaction(&nodes[2], &node_txn[0]);
2216 check_added_monitors!(nodes[2], 1);
2217 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2219 check_closed_broadcast!(nodes[2], true);
2220 assert_eq!(nodes[1].node.list_channels().len(), 0);
2221 assert_eq!(nodes[2].node.list_channels().len(), 1);
2222 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2223 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2225 macro_rules! claim_funds {
2226 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2228 $node.node.claim_funds($preimage);
2229 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2230 check_added_monitors!($node, 1);
2232 let events = $node.node.get_and_clear_pending_msg_events();
2233 assert_eq!(events.len(), 1);
2235 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2236 assert!(update_add_htlcs.is_empty());
2237 assert!(update_fail_htlcs.is_empty());
2238 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2240 _ => panic!("Unexpected event"),
2246 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2247 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2248 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2249 check_added_monitors!(nodes[2], 1);
2250 check_closed_broadcast!(nodes[2], true);
2251 let node2_commitment_txid;
2253 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2254 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2255 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2256 node2_commitment_txid = node_txn[0].txid();
2258 // Claim the payment on nodes[3], giving it knowledge of the preimage
2259 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2260 mine_transaction(&nodes[3], &node_txn[0]);
2261 check_added_monitors!(nodes[3], 1);
2262 check_preimage_claim(&nodes[3], &node_txn);
2264 check_closed_broadcast!(nodes[3], true);
2265 assert_eq!(nodes[2].node.list_channels().len(), 0);
2266 assert_eq!(nodes[3].node.list_channels().len(), 1);
2267 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2268 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2270 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2271 // confusing us in the following tests.
2272 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2274 // One pending HTLC to time out:
2275 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2276 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2279 let (close_chan_update_1, close_chan_update_2) = {
2280 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2281 let events = nodes[3].node.get_and_clear_pending_msg_events();
2282 assert_eq!(events.len(), 2);
2283 let close_chan_update_1 = match events[0] {
2284 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2287 _ => panic!("Unexpected event"),
2290 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2291 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2293 _ => panic!("Unexpected event"),
2295 check_added_monitors!(nodes[3], 1);
2297 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2299 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2300 node_txn.retain(|tx| {
2301 if tx.input[0].previous_output.txid == node2_commitment_txid {
2307 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2309 // Claim the payment on nodes[4], giving it knowledge of the preimage
2310 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2312 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2313 let events = nodes[4].node.get_and_clear_pending_msg_events();
2314 assert_eq!(events.len(), 2);
2315 let close_chan_update_2 = match events[0] {
2316 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2319 _ => panic!("Unexpected event"),
2322 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2323 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2325 _ => panic!("Unexpected event"),
2327 check_added_monitors!(nodes[4], 1);
2328 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2330 mine_transaction(&nodes[4], &node_txn[0]);
2331 check_preimage_claim(&nodes[4], &node_txn);
2332 (close_chan_update_1, close_chan_update_2)
2334 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2335 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2336 assert_eq!(nodes[3].node.list_channels().len(), 0);
2337 assert_eq!(nodes[4].node.list_channels().len(), 0);
2339 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2340 ChannelMonitorUpdateStatus::Completed);
2341 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2342 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2346 fn test_justice_tx() {
2347 // Test justice txn built on revoked HTLC-Success tx, against both sides
2348 let mut alice_config = UserConfig::default();
2349 alice_config.channel_handshake_config.announced_channel = true;
2350 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2351 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2352 let mut bob_config = UserConfig::default();
2353 bob_config.channel_handshake_config.announced_channel = true;
2354 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2355 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2356 let user_cfgs = [Some(alice_config), Some(bob_config)];
2357 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2358 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2359 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2363 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2364 // Create some new channels:
2365 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2367 // A pending HTLC which will be revoked:
2368 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2369 // Get the will-be-revoked local txn from nodes[0]
2370 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2371 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2372 assert_eq!(revoked_local_txn[0].input.len(), 1);
2373 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2374 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2375 assert_eq!(revoked_local_txn[1].input.len(), 1);
2376 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2377 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2378 // Revoke the old state
2379 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2382 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2384 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2385 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2386 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2388 check_spends!(node_txn[0], revoked_local_txn[0]);
2389 node_txn.swap_remove(0);
2390 node_txn.truncate(1);
2392 check_added_monitors!(nodes[1], 1);
2393 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2394 test_txn_broadcast(&nodes[1], &chan_5, None, 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(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment 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, None, 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(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2479 check_spends!(node_txn[0], revoked_local_txn[0]);
2480 check_spends!(node_txn[1], chan_1.3);
2482 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2483 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2484 get_announce_close_broadcast_events(&nodes, 0, 1);
2485 check_added_monitors!(nodes[0], 1);
2486 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2490 fn claim_htlc_outputs_shared_tx() {
2491 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2492 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2493 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2494 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2495 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2496 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2498 // Create some new channel:
2499 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2501 // Rebalance the network to generate htlc in the two directions
2502 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2503 // 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
2504 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2505 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2507 // Get the will-be-revoked local txn from node[0]
2508 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2509 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2510 assert_eq!(revoked_local_txn[0].input.len(), 1);
2511 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2512 assert_eq!(revoked_local_txn[1].input.len(), 1);
2513 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2514 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2515 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2517 //Revoke the old state
2518 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2521 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2522 check_added_monitors!(nodes[0], 1);
2523 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2524 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2525 check_added_monitors!(nodes[1], 1);
2526 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2527 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2528 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2530 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2531 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2533 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2534 check_spends!(node_txn[0], revoked_local_txn[0]);
2536 let mut witness_lens = BTreeSet::new();
2537 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2538 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2539 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2540 assert_eq!(witness_lens.len(), 3);
2541 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2542 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2543 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2545 // Next nodes[1] broadcasts its current local tx state:
2546 assert_eq!(node_txn[1].input.len(), 1);
2547 check_spends!(node_txn[1], chan_1.3);
2549 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2550 // ANTI_REORG_DELAY confirmations.
2551 mine_transaction(&nodes[1], &node_txn[0]);
2552 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2553 expect_payment_failed!(nodes[1], payment_hash_2, false);
2555 get_announce_close_broadcast_events(&nodes, 0, 1);
2556 assert_eq!(nodes[0].node.list_channels().len(), 0);
2557 assert_eq!(nodes[1].node.list_channels().len(), 0);
2561 fn claim_htlc_outputs_single_tx() {
2562 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2563 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2564 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2565 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2566 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2567 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2569 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2571 // Rebalance the network to generate htlc in the two directions
2572 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2573 // 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
2574 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2575 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2576 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2578 // Get the will-be-revoked local txn from node[0]
2579 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2581 //Revoke the old state
2582 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2585 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2586 check_added_monitors!(nodes[0], 1);
2587 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2588 check_added_monitors!(nodes[1], 1);
2589 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2590 let mut events = nodes[0].node.get_and_clear_pending_events();
2591 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2592 match events.last().unwrap() {
2593 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2594 _ => panic!("Unexpected event"),
2597 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2598 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2600 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2601 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2603 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2604 assert_eq!(node_txn[0].input.len(), 1);
2605 check_spends!(node_txn[0], chan_1.3);
2606 assert_eq!(node_txn[1].input.len(), 1);
2607 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2608 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2609 check_spends!(node_txn[1], node_txn[0]);
2611 // Justice transactions are indices 1-2-4
2612 assert_eq!(node_txn[2].input.len(), 1);
2613 assert_eq!(node_txn[3].input.len(), 1);
2614 assert_eq!(node_txn[4].input.len(), 1);
2616 check_spends!(node_txn[2], revoked_local_txn[0]);
2617 check_spends!(node_txn[3], revoked_local_txn[0]);
2618 check_spends!(node_txn[4], revoked_local_txn[0]);
2620 let mut witness_lens = BTreeSet::new();
2621 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2622 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2623 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2624 assert_eq!(witness_lens.len(), 3);
2625 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2626 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2627 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2629 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2630 // ANTI_REORG_DELAY confirmations.
2631 mine_transaction(&nodes[1], &node_txn[2]);
2632 mine_transaction(&nodes[1], &node_txn[3]);
2633 mine_transaction(&nodes[1], &node_txn[4]);
2634 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2635 expect_payment_failed!(nodes[1], payment_hash_2, false);
2637 get_announce_close_broadcast_events(&nodes, 0, 1);
2638 assert_eq!(nodes[0].node.list_channels().len(), 0);
2639 assert_eq!(nodes[1].node.list_channels().len(), 0);
2643 fn test_htlc_on_chain_success() {
2644 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2645 // the preimage backward accordingly. So here we test that ChannelManager is
2646 // broadcasting the right event to other nodes in payment path.
2647 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2648 // A --------------------> B ----------------------> C (preimage)
2649 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2650 // commitment transaction was broadcast.
2651 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2653 // B should be able to claim via preimage if A then broadcasts its local tx.
2654 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2655 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2656 // PaymentSent event).
2658 let chanmon_cfgs = create_chanmon_cfgs(3);
2659 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2660 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2661 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2663 // Create some initial channels
2664 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2665 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2667 // Ensure all nodes are at the same height
2668 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2669 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2670 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2671 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2673 // Rebalance the network a bit by relaying one payment through all the channels...
2674 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2675 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2677 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2678 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2680 // Broadcast legit commitment tx from C on B's chain
2681 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2682 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2683 assert_eq!(commitment_tx.len(), 1);
2684 check_spends!(commitment_tx[0], chan_2.3);
2685 nodes[2].node.claim_funds(our_payment_preimage);
2686 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2687 nodes[2].node.claim_funds(our_payment_preimage_2);
2688 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2689 check_added_monitors!(nodes[2], 2);
2690 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2691 assert!(updates.update_add_htlcs.is_empty());
2692 assert!(updates.update_fail_htlcs.is_empty());
2693 assert!(updates.update_fail_malformed_htlcs.is_empty());
2694 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2696 mine_transaction(&nodes[2], &commitment_tx[0]);
2697 check_closed_broadcast!(nodes[2], true);
2698 check_added_monitors!(nodes[2], 1);
2699 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2700 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2701 assert_eq!(node_txn.len(), 5);
2702 assert_eq!(node_txn[0], node_txn[3]);
2703 assert_eq!(node_txn[1], node_txn[4]);
2704 assert_eq!(node_txn[2], commitment_tx[0]);
2705 check_spends!(node_txn[0], commitment_tx[0]);
2706 check_spends!(node_txn[1], commitment_tx[0]);
2707 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2708 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2709 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2710 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2711 assert_eq!(node_txn[0].lock_time.0, 0);
2712 assert_eq!(node_txn[1].lock_time.0, 0);
2714 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2715 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2716 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2717 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2719 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2720 assert_eq!(added_monitors.len(), 1);
2721 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2722 added_monitors.clear();
2724 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2725 assert_eq!(forwarded_events.len(), 3);
2726 match forwarded_events[0] {
2727 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2728 _ => panic!("Unexpected event"),
2730 let chan_id = Some(chan_1.2);
2731 match forwarded_events[1] {
2732 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2733 assert_eq!(fee_earned_msat, Some(1000));
2734 assert_eq!(prev_channel_id, chan_id);
2735 assert_eq!(claim_from_onchain_tx, true);
2736 assert_eq!(next_channel_id, Some(chan_2.2));
2740 match forwarded_events[2] {
2741 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2742 assert_eq!(fee_earned_msat, Some(1000));
2743 assert_eq!(prev_channel_id, chan_id);
2744 assert_eq!(claim_from_onchain_tx, true);
2745 assert_eq!(next_channel_id, Some(chan_2.2));
2749 let events = nodes[1].node.get_and_clear_pending_msg_events();
2751 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2752 assert_eq!(added_monitors.len(), 2);
2753 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2754 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2755 added_monitors.clear();
2757 assert_eq!(events.len(), 3);
2759 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2760 _ => panic!("Unexpected event"),
2763 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2764 _ => panic!("Unexpected event"),
2768 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, .. } } => {
2769 assert!(update_add_htlcs.is_empty());
2770 assert!(update_fail_htlcs.is_empty());
2771 assert_eq!(update_fulfill_htlcs.len(), 1);
2772 assert!(update_fail_malformed_htlcs.is_empty());
2773 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2775 _ => panic!("Unexpected event"),
2777 macro_rules! check_tx_local_broadcast {
2778 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2779 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2780 assert_eq!(node_txn.len(), 3);
2781 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2782 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2783 check_spends!(node_txn[1], $commitment_tx);
2784 check_spends!(node_txn[2], $commitment_tx);
2785 assert_ne!(node_txn[1].lock_time.0, 0);
2786 assert_ne!(node_txn[2].lock_time.0, 0);
2788 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2789 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2790 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2791 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2793 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2794 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2795 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2796 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2798 check_spends!(node_txn[0], $chan_tx);
2799 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2803 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2804 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2805 // timeout-claim of the output that nodes[2] just claimed via success.
2806 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2808 // Broadcast legit commitment tx from A on B's chain
2809 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2810 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2811 check_spends!(node_a_commitment_tx[0], chan_1.3);
2812 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2813 check_closed_broadcast!(nodes[1], true);
2814 check_added_monitors!(nodes[1], 1);
2815 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2816 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2817 assert!(node_txn.len() == 4 || node_txn.len() == 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2818 let commitment_spend =
2819 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2820 if node_txn.len() == 6 {
2821 // In some block `ConnectionStyle`s we may avoid broadcasting the double-spending
2822 // transactions spending the HTLC outputs of C's commitment transaction. Otherwise,
2823 // check that the extra broadcasts (double-)spend those here.
2824 check_spends!(node_txn[1], commitment_tx[0]);
2825 check_spends!(node_txn[2], commitment_tx[0]);
2826 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2830 check_spends!(node_txn[0], commitment_tx[0]);
2831 check_spends!(node_txn[1], commitment_tx[0]);
2832 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2836 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2837 assert_eq!(commitment_spend.input.len(), 2);
2838 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2839 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2840 assert_eq!(commitment_spend.lock_time.0, 0);
2841 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2842 let funding_spend_offset = if node_txn.len() == 6 { 3 } else { 1 };
2843 check_spends!(node_txn[funding_spend_offset], chan_1.3);
2844 assert_eq!(node_txn[funding_spend_offset].input[0].witness.clone().last().unwrap().len(), 71);
2845 check_spends!(node_txn[funding_spend_offset + 1], node_txn[funding_spend_offset]);
2846 check_spends!(node_txn[funding_spend_offset + 2], node_txn[funding_spend_offset]);
2847 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2848 // we already checked the same situation with A.
2850 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2851 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2852 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2853 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2854 check_closed_broadcast!(nodes[0], true);
2855 check_added_monitors!(nodes[0], 1);
2856 let events = nodes[0].node.get_and_clear_pending_events();
2857 assert_eq!(events.len(), 5);
2858 let mut first_claimed = false;
2859 for event in events {
2861 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2862 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2863 assert!(!first_claimed);
2864 first_claimed = true;
2866 assert_eq!(payment_preimage, our_payment_preimage_2);
2867 assert_eq!(payment_hash, payment_hash_2);
2870 Event::PaymentPathSuccessful { .. } => {},
2871 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2872 _ => panic!("Unexpected event"),
2875 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2878 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2879 // Test that in case of a unilateral close onchain, we detect the state of output and
2880 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2881 // broadcasting the right event to other nodes in payment path.
2882 // A ------------------> B ----------------------> C (timeout)
2883 // B's commitment tx C's commitment tx
2885 // B's HTLC timeout tx B's timeout tx
2887 let chanmon_cfgs = create_chanmon_cfgs(3);
2888 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2889 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2890 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2891 *nodes[0].connect_style.borrow_mut() = connect_style;
2892 *nodes[1].connect_style.borrow_mut() = connect_style;
2893 *nodes[2].connect_style.borrow_mut() = connect_style;
2895 // Create some intial channels
2896 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2897 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2899 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2900 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2901 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2903 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2905 // Broadcast legit commitment tx from C on B's chain
2906 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2907 check_spends!(commitment_tx[0], chan_2.3);
2908 nodes[2].node.fail_htlc_backwards(&payment_hash);
2909 check_added_monitors!(nodes[2], 0);
2910 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2911 check_added_monitors!(nodes[2], 1);
2913 let events = nodes[2].node.get_and_clear_pending_msg_events();
2914 assert_eq!(events.len(), 1);
2916 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, .. } } => {
2917 assert!(update_add_htlcs.is_empty());
2918 assert!(!update_fail_htlcs.is_empty());
2919 assert!(update_fulfill_htlcs.is_empty());
2920 assert!(update_fail_malformed_htlcs.is_empty());
2921 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2923 _ => panic!("Unexpected event"),
2925 mine_transaction(&nodes[2], &commitment_tx[0]);
2926 check_closed_broadcast!(nodes[2], true);
2927 check_added_monitors!(nodes[2], 1);
2928 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2929 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2930 assert_eq!(node_txn.len(), 1);
2931 check_spends!(node_txn[0], chan_2.3);
2932 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2934 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2935 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2936 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2937 mine_transaction(&nodes[1], &commitment_tx[0]);
2938 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2941 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2942 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2943 assert_eq!(node_txn[0], node_txn[3]);
2944 assert_eq!(node_txn[1], node_txn[4]);
2946 check_spends!(node_txn[2], commitment_tx[0]);
2947 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2949 check_spends!(node_txn[0], chan_2.3);
2950 check_spends!(node_txn[1], node_txn[0]);
2951 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2952 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2954 timeout_tx = node_txn[2].clone();
2958 mine_transaction(&nodes[1], &timeout_tx);
2959 check_added_monitors!(nodes[1], 1);
2960 check_closed_broadcast!(nodes[1], true);
2962 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2964 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 }]);
2965 check_added_monitors!(nodes[1], 1);
2966 let events = nodes[1].node.get_and_clear_pending_msg_events();
2967 assert_eq!(events.len(), 1);
2969 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, .. } } => {
2970 assert!(update_add_htlcs.is_empty());
2971 assert!(!update_fail_htlcs.is_empty());
2972 assert!(update_fulfill_htlcs.is_empty());
2973 assert!(update_fail_malformed_htlcs.is_empty());
2974 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2976 _ => panic!("Unexpected event"),
2979 // Broadcast legit commitment tx from B on A's chain
2980 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2981 check_spends!(commitment_tx[0], chan_1.3);
2983 mine_transaction(&nodes[0], &commitment_tx[0]);
2984 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2986 check_closed_broadcast!(nodes[0], true);
2987 check_added_monitors!(nodes[0], 1);
2988 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2989 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2990 assert_eq!(node_txn.len(), 2);
2991 check_spends!(node_txn[0], chan_1.3);
2992 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2993 check_spends!(node_txn[1], commitment_tx[0]);
2994 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2998 fn test_htlc_on_chain_timeout() {
2999 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3000 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3001 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3005 fn test_simple_commitment_revoked_fail_backward() {
3006 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3007 // and fail backward accordingly.
3009 let chanmon_cfgs = create_chanmon_cfgs(3);
3010 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3011 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3012 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3014 // Create some initial channels
3015 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3016 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3018 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3019 // Get the will-be-revoked local txn from nodes[2]
3020 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3021 // Revoke the old state
3022 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3024 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3026 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3027 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3028 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3029 check_added_monitors!(nodes[1], 1);
3030 check_closed_broadcast!(nodes[1], true);
3032 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 }]);
3033 check_added_monitors!(nodes[1], 1);
3034 let events = nodes[1].node.get_and_clear_pending_msg_events();
3035 assert_eq!(events.len(), 1);
3037 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, .. } } => {
3038 assert!(update_add_htlcs.is_empty());
3039 assert_eq!(update_fail_htlcs.len(), 1);
3040 assert!(update_fulfill_htlcs.is_empty());
3041 assert!(update_fail_malformed_htlcs.is_empty());
3042 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3044 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3045 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3046 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3048 _ => panic!("Unexpected event"),
3052 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3053 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3054 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3055 // commitment transaction anymore.
3056 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3057 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3058 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3059 // technically disallowed and we should probably handle it reasonably.
3060 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3061 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3063 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3064 // commitment_signed (implying it will be in the latest remote commitment transaction).
3065 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3066 // and once they revoke the previous commitment transaction (allowing us to send a new
3067 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3068 let chanmon_cfgs = create_chanmon_cfgs(3);
3069 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3070 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3071 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3073 // Create some initial channels
3074 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3075 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3077 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 });
3078 // Get the will-be-revoked local txn from nodes[2]
3079 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3080 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3081 // Revoke the old state
3082 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3084 let value = if use_dust {
3085 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3086 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3087 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3090 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3091 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3092 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3094 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3095 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3096 check_added_monitors!(nodes[2], 1);
3097 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3098 assert!(updates.update_add_htlcs.is_empty());
3099 assert!(updates.update_fulfill_htlcs.is_empty());
3100 assert!(updates.update_fail_malformed_htlcs.is_empty());
3101 assert_eq!(updates.update_fail_htlcs.len(), 1);
3102 assert!(updates.update_fee.is_none());
3103 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3104 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3105 // Drop the last RAA from 3 -> 2
3107 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3108 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3109 check_added_monitors!(nodes[2], 1);
3110 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3111 assert!(updates.update_add_htlcs.is_empty());
3112 assert!(updates.update_fulfill_htlcs.is_empty());
3113 assert!(updates.update_fail_malformed_htlcs.is_empty());
3114 assert_eq!(updates.update_fail_htlcs.len(), 1);
3115 assert!(updates.update_fee.is_none());
3116 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3117 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3118 check_added_monitors!(nodes[1], 1);
3119 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3120 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3121 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3122 check_added_monitors!(nodes[2], 1);
3124 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3125 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3126 check_added_monitors!(nodes[2], 1);
3127 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3128 assert!(updates.update_add_htlcs.is_empty());
3129 assert!(updates.update_fulfill_htlcs.is_empty());
3130 assert!(updates.update_fail_malformed_htlcs.is_empty());
3131 assert_eq!(updates.update_fail_htlcs.len(), 1);
3132 assert!(updates.update_fee.is_none());
3133 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3134 // At this point first_payment_hash has dropped out of the latest two commitment
3135 // transactions that nodes[1] is tracking...
3136 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3137 check_added_monitors!(nodes[1], 1);
3138 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3139 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3140 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3141 check_added_monitors!(nodes[2], 1);
3143 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3144 // on nodes[2]'s RAA.
3145 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3146 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3147 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3148 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3149 check_added_monitors!(nodes[1], 0);
3152 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3153 // One monitor for the new revocation preimage, no second on as we won't generate a new
3154 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3155 check_added_monitors!(nodes[1], 1);
3156 let events = nodes[1].node.get_and_clear_pending_events();
3157 assert_eq!(events.len(), 2);
3159 Event::PendingHTLCsForwardable { .. } => { },
3160 _ => panic!("Unexpected event"),
3163 Event::HTLCHandlingFailed { .. } => { },
3164 _ => panic!("Unexpected event"),
3166 // Deliberately don't process the pending fail-back so they all fail back at once after
3167 // block connection just like the !deliver_bs_raa case
3170 let mut failed_htlcs = HashSet::new();
3171 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3173 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3174 check_added_monitors!(nodes[1], 1);
3175 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3177 let events = nodes[1].node.get_and_clear_pending_events();
3178 assert_eq!(events.len(), if deliver_bs_raa { 2 + nodes.len() - 1 } else { 3 + nodes.len() });
3180 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3181 _ => panic!("Unexepected event"),
3184 Event::PaymentPathFailed { ref payment_hash, .. } => {
3185 assert_eq!(*payment_hash, fourth_payment_hash);
3187 _ => panic!("Unexpected event"),
3189 if !deliver_bs_raa {
3191 Event::PendingHTLCsForwardable { .. } => { },
3192 _ => panic!("Unexpected event"),
3194 nodes[1].node.abandon_payment(PaymentId(fourth_payment_hash.0));
3195 let payment_failed_events = nodes[1].node.get_and_clear_pending_events();
3196 assert_eq!(payment_failed_events.len(), 1);
3197 match payment_failed_events[0] {
3198 Event::PaymentFailed { ref payment_hash, .. } => {
3199 assert_eq!(*payment_hash, fourth_payment_hash);
3201 _ => panic!("Unexpected event"),
3204 nodes[1].node.process_pending_htlc_forwards();
3205 check_added_monitors!(nodes[1], 1);
3207 let events = nodes[1].node.get_and_clear_pending_msg_events();
3208 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3209 match events[if deliver_bs_raa { 1 } else { 0 }] {
3210 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3211 _ => panic!("Unexpected event"),
3213 match events[if deliver_bs_raa { 2 } else { 1 }] {
3214 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3215 assert_eq!(channel_id, chan_2.2);
3216 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3218 _ => panic!("Unexpected event"),
3222 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, .. } } => {
3223 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3224 assert_eq!(update_add_htlcs.len(), 1);
3225 assert!(update_fulfill_htlcs.is_empty());
3226 assert!(update_fail_htlcs.is_empty());
3227 assert!(update_fail_malformed_htlcs.is_empty());
3229 _ => panic!("Unexpected event"),
3232 match events[if deliver_bs_raa { 3 } else { 2 }] {
3233 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, .. } } => {
3234 assert!(update_add_htlcs.is_empty());
3235 assert_eq!(update_fail_htlcs.len(), 3);
3236 assert!(update_fulfill_htlcs.is_empty());
3237 assert!(update_fail_malformed_htlcs.is_empty());
3238 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3240 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3241 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3242 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3244 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3246 let events = nodes[0].node.get_and_clear_pending_events();
3247 assert_eq!(events.len(), 3);
3249 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3250 assert!(failed_htlcs.insert(payment_hash.0));
3251 // If we delivered B's RAA we got an unknown preimage error, not something
3252 // that we should update our routing table for.
3253 if !deliver_bs_raa {
3254 assert!(network_update.is_some());
3257 _ => panic!("Unexpected event"),
3260 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3261 assert!(failed_htlcs.insert(payment_hash.0));
3262 assert!(network_update.is_some());
3264 _ => panic!("Unexpected event"),
3267 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3268 assert!(failed_htlcs.insert(payment_hash.0));
3269 assert!(network_update.is_some());
3271 _ => panic!("Unexpected event"),
3274 _ => panic!("Unexpected event"),
3277 assert!(failed_htlcs.contains(&first_payment_hash.0));
3278 assert!(failed_htlcs.contains(&second_payment_hash.0));
3279 assert!(failed_htlcs.contains(&third_payment_hash.0));
3283 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3284 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3285 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3286 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3287 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3291 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3292 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3293 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3294 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3295 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3299 fn fail_backward_pending_htlc_upon_channel_failure() {
3300 let chanmon_cfgs = create_chanmon_cfgs(2);
3301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3303 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3304 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());
3306 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3308 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3309 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3310 check_added_monitors!(nodes[0], 1);
3312 let payment_event = {
3313 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3314 assert_eq!(events.len(), 1);
3315 SendEvent::from_event(events.remove(0))
3317 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3318 assert_eq!(payment_event.msgs.len(), 1);
3321 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3322 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3324 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3325 check_added_monitors!(nodes[0], 0);
3327 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3330 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3332 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3334 let secp_ctx = Secp256k1::new();
3335 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3336 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3337 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3338 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3339 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3341 // Send a 0-msat update_add_htlc to fail the channel.
3342 let update_add_htlc = msgs::UpdateAddHTLC {
3348 onion_routing_packet,
3350 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3352 let events = nodes[0].node.get_and_clear_pending_events();
3353 assert_eq!(events.len(), 2);
3354 // Check that Alice fails backward the pending HTLC from the second payment.
3356 Event::PaymentPathFailed { payment_hash, .. } => {
3357 assert_eq!(payment_hash, failed_payment_hash);
3359 _ => panic!("Unexpected event"),
3362 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3363 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3365 _ => panic!("Unexpected event {:?}", events[1]),
3367 check_closed_broadcast!(nodes[0], true);
3368 check_added_monitors!(nodes[0], 1);
3372 fn test_htlc_ignore_latest_remote_commitment() {
3373 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3374 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3375 let chanmon_cfgs = create_chanmon_cfgs(2);
3376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3378 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3379 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3380 // We rely on the ability to connect a block redundantly, which isn't allowed via
3381 // `chain::Listen`, so we never run the test if we randomly get assigned that
3385 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3387 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3388 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3389 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3390 check_closed_broadcast!(nodes[0], true);
3391 check_added_monitors!(nodes[0], 1);
3392 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3394 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3395 assert_eq!(node_txn.len(), 3);
3396 assert_eq!(node_txn[0], node_txn[1]);
3398 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3399 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3400 check_closed_broadcast!(nodes[1], true);
3401 check_added_monitors!(nodes[1], 1);
3402 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3404 // Duplicate the connect_block call since this may happen due to other listeners
3405 // registering new transactions
3406 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3410 fn test_force_close_fail_back() {
3411 // Check which HTLCs are failed-backwards on channel force-closure
3412 let chanmon_cfgs = create_chanmon_cfgs(3);
3413 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3414 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3415 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3416 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3417 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3419 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3421 let mut payment_event = {
3422 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3423 check_added_monitors!(nodes[0], 1);
3425 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3426 assert_eq!(events.len(), 1);
3427 SendEvent::from_event(events.remove(0))
3430 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3431 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3433 expect_pending_htlcs_forwardable!(nodes[1]);
3435 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3436 assert_eq!(events_2.len(), 1);
3437 payment_event = SendEvent::from_event(events_2.remove(0));
3438 assert_eq!(payment_event.msgs.len(), 1);
3440 check_added_monitors!(nodes[1], 1);
3441 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3442 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3443 check_added_monitors!(nodes[2], 1);
3444 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3446 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3447 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3448 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3450 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3451 check_closed_broadcast!(nodes[2], true);
3452 check_added_monitors!(nodes[2], 1);
3453 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3455 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3456 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3457 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3458 // back to nodes[1] upon timeout otherwise.
3459 assert_eq!(node_txn.len(), 1);
3463 mine_transaction(&nodes[1], &tx);
3465 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3466 check_closed_broadcast!(nodes[1], true);
3467 check_added_monitors!(nodes[1], 1);
3468 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3470 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3472 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3473 .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);
3475 mine_transaction(&nodes[2], &tx);
3476 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3477 assert_eq!(node_txn.len(), 1);
3478 assert_eq!(node_txn[0].input.len(), 1);
3479 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3480 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3481 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3483 check_spends!(node_txn[0], tx);
3487 fn test_dup_events_on_peer_disconnect() {
3488 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3489 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3490 // as we used to generate the event immediately upon receipt of the payment preimage in the
3491 // update_fulfill_htlc message.
3493 let chanmon_cfgs = create_chanmon_cfgs(2);
3494 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3495 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3496 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3497 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3499 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3501 nodes[1].node.claim_funds(payment_preimage);
3502 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3503 check_added_monitors!(nodes[1], 1);
3504 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3505 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3506 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3508 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3509 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3511 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3512 expect_payment_path_successful!(nodes[0]);
3516 fn test_peer_disconnected_before_funding_broadcasted() {
3517 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3518 // before the funding transaction has been broadcasted.
3519 let chanmon_cfgs = create_chanmon_cfgs(2);
3520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3524 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3525 // broadcasted, even though it's created by `nodes[0]`.
3526 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();
3527 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3528 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3529 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3530 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3532 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3533 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3535 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3537 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3538 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3540 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3541 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3544 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3547 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3548 // disconnected before the funding transaction was broadcasted.
3549 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3550 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3552 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3553 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3557 fn test_simple_peer_disconnect() {
3558 // Test that we can reconnect when there are no lost messages
3559 let chanmon_cfgs = create_chanmon_cfgs(3);
3560 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3561 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3562 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3563 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3564 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3566 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3567 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3568 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3570 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3571 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3572 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3573 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3575 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3576 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3577 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3579 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3580 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3581 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3582 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3584 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3585 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3587 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3588 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3590 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3592 let events = nodes[0].node.get_and_clear_pending_events();
3593 assert_eq!(events.len(), 3);
3595 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3596 assert_eq!(payment_preimage, payment_preimage_3);
3597 assert_eq!(payment_hash, payment_hash_3);
3599 _ => panic!("Unexpected event"),
3602 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3603 assert_eq!(payment_hash, payment_hash_5);
3604 assert!(payment_failed_permanently);
3606 _ => panic!("Unexpected event"),
3609 Event::PaymentPathSuccessful { .. } => {},
3610 _ => panic!("Unexpected event"),
3614 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3615 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3618 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3619 // Test that we can reconnect when in-flight HTLC updates get dropped
3620 let chanmon_cfgs = create_chanmon_cfgs(2);
3621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3623 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3625 let mut as_channel_ready = None;
3626 if messages_delivered == 0 {
3627 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3628 as_channel_ready = Some(channel_ready);
3629 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3630 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3631 // it before the channel_reestablish message.
3633 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3636 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3638 let payment_event = {
3639 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3640 check_added_monitors!(nodes[0], 1);
3642 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3643 assert_eq!(events.len(), 1);
3644 SendEvent::from_event(events.remove(0))
3646 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3648 if messages_delivered < 2 {
3649 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3651 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3652 if messages_delivered >= 3 {
3653 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3654 check_added_monitors!(nodes[1], 1);
3655 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3657 if messages_delivered >= 4 {
3658 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3659 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3660 check_added_monitors!(nodes[0], 1);
3662 if messages_delivered >= 5 {
3663 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3664 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3665 // No commitment_signed so get_event_msg's assert(len == 1) passes
3666 check_added_monitors!(nodes[0], 1);
3668 if messages_delivered >= 6 {
3669 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3670 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3671 check_added_monitors!(nodes[1], 1);
3678 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3679 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3680 if messages_delivered < 3 {
3681 if simulate_broken_lnd {
3682 // lnd has a long-standing bug where they send a channel_ready prior to a
3683 // channel_reestablish if you reconnect prior to channel_ready time.
3685 // Here we simulate that behavior, delivering a channel_ready immediately on
3686 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3687 // in `reconnect_nodes` but we currently don't fail based on that.
3689 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3690 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3692 // Even if the channel_ready messages get exchanged, as long as nothing further was
3693 // received on either side, both sides will need to resend them.
3694 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3695 } else if messages_delivered == 3 {
3696 // nodes[0] still wants its RAA + commitment_signed
3697 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3698 } else if messages_delivered == 4 {
3699 // nodes[0] still wants its commitment_signed
3700 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701 } else if messages_delivered == 5 {
3702 // nodes[1] still wants its final RAA
3703 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3704 } else if messages_delivered == 6 {
3705 // Everything was delivered...
3706 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3709 let events_1 = nodes[1].node.get_and_clear_pending_events();
3710 if messages_delivered == 0 {
3711 assert_eq!(events_1.len(), 2);
3713 Event::ChannelReady { .. } => { },
3714 _ => panic!("Unexpected event"),
3717 Event::PendingHTLCsForwardable { .. } => { },
3718 _ => panic!("Unexpected event"),
3721 assert_eq!(events_1.len(), 1);
3723 Event::PendingHTLCsForwardable { .. } => { },
3724 _ => panic!("Unexpected event"),
3728 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3729 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3730 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3732 nodes[1].node.process_pending_htlc_forwards();
3734 let events_2 = nodes[1].node.get_and_clear_pending_events();
3735 assert_eq!(events_2.len(), 1);
3737 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3738 assert_eq!(payment_hash_1, *payment_hash);
3739 assert_eq!(amount_msat, 1_000_000);
3741 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3742 assert!(payment_preimage.is_none());
3743 assert_eq!(payment_secret_1, *payment_secret);
3745 _ => panic!("expected PaymentPurpose::InvoicePayment")
3748 _ => panic!("Unexpected event"),
3751 nodes[1].node.claim_funds(payment_preimage_1);
3752 check_added_monitors!(nodes[1], 1);
3753 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3755 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3756 assert_eq!(events_3.len(), 1);
3757 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3758 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3759 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3760 assert!(updates.update_add_htlcs.is_empty());
3761 assert!(updates.update_fail_htlcs.is_empty());
3762 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3763 assert!(updates.update_fail_malformed_htlcs.is_empty());
3764 assert!(updates.update_fee.is_none());
3765 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3767 _ => panic!("Unexpected event"),
3770 if messages_delivered >= 1 {
3771 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3773 let events_4 = nodes[0].node.get_and_clear_pending_events();
3774 assert_eq!(events_4.len(), 1);
3776 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3777 assert_eq!(payment_preimage_1, *payment_preimage);
3778 assert_eq!(payment_hash_1, *payment_hash);
3780 _ => panic!("Unexpected event"),
3783 if messages_delivered >= 2 {
3784 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3785 check_added_monitors!(nodes[0], 1);
3786 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3788 if messages_delivered >= 3 {
3789 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3790 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3791 check_added_monitors!(nodes[1], 1);
3793 if messages_delivered >= 4 {
3794 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3795 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3796 // No commitment_signed so get_event_msg's assert(len == 1) passes
3797 check_added_monitors!(nodes[1], 1);
3799 if messages_delivered >= 5 {
3800 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3801 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3802 check_added_monitors!(nodes[0], 1);
3809 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3810 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3811 if messages_delivered < 2 {
3812 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3813 if messages_delivered < 1 {
3814 expect_payment_sent!(nodes[0], payment_preimage_1);
3816 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3818 } else if messages_delivered == 2 {
3819 // nodes[0] still wants its RAA + commitment_signed
3820 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3821 } else if messages_delivered == 3 {
3822 // nodes[0] still wants its commitment_signed
3823 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3824 } else if messages_delivered == 4 {
3825 // nodes[1] still wants its final RAA
3826 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3827 } else if messages_delivered == 5 {
3828 // Everything was delivered...
3829 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3832 if messages_delivered == 1 || messages_delivered == 2 {
3833 expect_payment_path_successful!(nodes[0]);
3836 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3837 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3838 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3840 if messages_delivered > 2 {
3841 expect_payment_path_successful!(nodes[0]);
3844 // Channel should still work fine...
3845 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3846 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3847 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3851 fn test_drop_messages_peer_disconnect_a() {
3852 do_test_drop_messages_peer_disconnect(0, true);
3853 do_test_drop_messages_peer_disconnect(0, false);
3854 do_test_drop_messages_peer_disconnect(1, false);
3855 do_test_drop_messages_peer_disconnect(2, false);
3859 fn test_drop_messages_peer_disconnect_b() {
3860 do_test_drop_messages_peer_disconnect(3, false);
3861 do_test_drop_messages_peer_disconnect(4, false);
3862 do_test_drop_messages_peer_disconnect(5, false);
3863 do_test_drop_messages_peer_disconnect(6, false);
3867 fn test_channel_ready_without_best_block_updated() {
3868 // Previously, if we were offline when a funding transaction was locked in, and then we came
3869 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3870 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3871 // channel_ready immediately instead.
3872 let chanmon_cfgs = create_chanmon_cfgs(2);
3873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3875 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3876 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3878 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());
3880 let conf_height = nodes[0].best_block_info().1 + 1;
3881 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3882 let block_txn = [funding_tx];
3883 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3884 let conf_block_header = nodes[0].get_block_header(conf_height);
3885 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3887 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3888 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3889 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3893 fn test_drop_messages_peer_disconnect_dual_htlc() {
3894 // Test that we can handle reconnecting when both sides of a channel have pending
3895 // commitment_updates when we disconnect.
3896 let chanmon_cfgs = create_chanmon_cfgs(2);
3897 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3898 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3899 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3900 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3902 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3904 // Now try to send a second payment which will fail to send
3905 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3906 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3907 check_added_monitors!(nodes[0], 1);
3909 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3910 assert_eq!(events_1.len(), 1);
3912 MessageSendEvent::UpdateHTLCs { .. } => {},
3913 _ => panic!("Unexpected event"),
3916 nodes[1].node.claim_funds(payment_preimage_1);
3917 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3918 check_added_monitors!(nodes[1], 1);
3920 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3921 assert_eq!(events_2.len(), 1);
3923 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 } } => {
3924 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3925 assert!(update_add_htlcs.is_empty());
3926 assert_eq!(update_fulfill_htlcs.len(), 1);
3927 assert!(update_fail_htlcs.is_empty());
3928 assert!(update_fail_malformed_htlcs.is_empty());
3929 assert!(update_fee.is_none());
3931 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3932 let events_3 = nodes[0].node.get_and_clear_pending_events();
3933 assert_eq!(events_3.len(), 1);
3935 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3936 assert_eq!(*payment_preimage, payment_preimage_1);
3937 assert_eq!(*payment_hash, payment_hash_1);
3939 _ => panic!("Unexpected event"),
3942 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3943 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3944 // No commitment_signed so get_event_msg's assert(len == 1) passes
3945 check_added_monitors!(nodes[0], 1);
3947 _ => panic!("Unexpected event"),
3950 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3951 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3953 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3954 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3955 assert_eq!(reestablish_1.len(), 1);
3956 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3957 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3958 assert_eq!(reestablish_2.len(), 1);
3960 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3961 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3962 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3963 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3965 assert!(as_resp.0.is_none());
3966 assert!(bs_resp.0.is_none());
3968 assert!(bs_resp.1.is_none());
3969 assert!(bs_resp.2.is_none());
3971 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3973 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3974 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3975 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3976 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3977 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3978 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3979 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3980 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3981 // No commitment_signed so get_event_msg's assert(len == 1) passes
3982 check_added_monitors!(nodes[1], 1);
3984 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3985 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3986 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3987 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3988 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3989 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3990 assert!(bs_second_commitment_signed.update_fee.is_none());
3991 check_added_monitors!(nodes[1], 1);
3993 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3994 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3995 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3996 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3997 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3998 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3999 assert!(as_commitment_signed.update_fee.is_none());
4000 check_added_monitors!(nodes[0], 1);
4002 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4003 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4004 // No commitment_signed so get_event_msg's assert(len == 1) passes
4005 check_added_monitors!(nodes[0], 1);
4007 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4008 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4009 // No commitment_signed so get_event_msg's assert(len == 1) passes
4010 check_added_monitors!(nodes[1], 1);
4012 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4013 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4014 check_added_monitors!(nodes[1], 1);
4016 expect_pending_htlcs_forwardable!(nodes[1]);
4018 let events_5 = nodes[1].node.get_and_clear_pending_events();
4019 assert_eq!(events_5.len(), 1);
4021 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4022 assert_eq!(payment_hash_2, *payment_hash);
4024 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4025 assert!(payment_preimage.is_none());
4026 assert_eq!(payment_secret_2, *payment_secret);
4028 _ => panic!("expected PaymentPurpose::InvoicePayment")
4031 _ => panic!("Unexpected event"),
4034 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4035 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4036 check_added_monitors!(nodes[0], 1);
4038 expect_payment_path_successful!(nodes[0]);
4039 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4042 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4043 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4044 // to avoid our counterparty failing the channel.
4045 let chanmon_cfgs = create_chanmon_cfgs(2);
4046 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4047 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4048 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4050 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4052 let our_payment_hash = if send_partial_mpp {
4053 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4054 // Use the utility function send_payment_along_path to send the payment with MPP data which
4055 // indicates there are more HTLCs coming.
4056 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.
4057 let payment_id = PaymentId([42; 32]);
4058 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4059 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();
4060 check_added_monitors!(nodes[0], 1);
4061 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4062 assert_eq!(events.len(), 1);
4063 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4064 // hop should *not* yet generate any PaymentReceived event(s).
4065 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4068 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4071 let mut block = Block {
4072 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4075 connect_block(&nodes[0], &block);
4076 connect_block(&nodes[1], &block);
4077 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4078 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4079 block.header.prev_blockhash = block.block_hash();
4080 connect_block(&nodes[0], &block);
4081 connect_block(&nodes[1], &block);
4084 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4086 check_added_monitors!(nodes[1], 1);
4087 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4088 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4089 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4090 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4091 assert!(htlc_timeout_updates.update_fee.is_none());
4093 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4094 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4095 // 100_000 msat as u64, followed by the height at which we failed back above
4096 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4097 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4098 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4102 fn test_htlc_timeout() {
4103 do_test_htlc_timeout(true);
4104 do_test_htlc_timeout(false);
4107 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4108 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4109 let chanmon_cfgs = create_chanmon_cfgs(3);
4110 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4111 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4112 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4113 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4114 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4116 // Make sure all nodes are at the same starting height
4117 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4118 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4119 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4121 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4122 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4124 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4126 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4127 check_added_monitors!(nodes[1], 1);
4129 // Now attempt to route a second payment, which should be placed in the holding cell
4130 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4131 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4132 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4134 check_added_monitors!(nodes[0], 1);
4135 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4136 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4137 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4138 expect_pending_htlcs_forwardable!(nodes[1]);
4140 check_added_monitors!(nodes[1], 0);
4142 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4143 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4144 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4145 connect_blocks(&nodes[1], 1);
4148 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 }]);
4149 check_added_monitors!(nodes[1], 1);
4150 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4151 assert_eq!(fail_commit.len(), 1);
4152 match fail_commit[0] {
4153 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4154 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4155 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4157 _ => unreachable!(),
4159 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4161 expect_payment_failed!(nodes[1], second_payment_hash, false);
4166 fn test_holding_cell_htlc_add_timeouts() {
4167 do_test_holding_cell_htlc_add_timeouts(false);
4168 do_test_holding_cell_htlc_add_timeouts(true);
4171 macro_rules! check_spendable_outputs {
4172 ($node: expr, $keysinterface: expr) => {
4174 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4175 let mut txn = Vec::new();
4176 let mut all_outputs = Vec::new();
4177 let secp_ctx = Secp256k1::new();
4178 for event in events.drain(..) {
4180 Event::SpendableOutputs { mut outputs } => {
4181 for outp in outputs.drain(..) {
4182 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4183 all_outputs.push(outp);
4186 _ => panic!("Unexpected event"),
4189 if all_outputs.len() > 1 {
4190 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) {
4200 fn test_claim_sizeable_push_msat() {
4201 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4202 let chanmon_cfgs = create_chanmon_cfgs(2);
4203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4205 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4207 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());
4208 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4209 check_closed_broadcast!(nodes[1], true);
4210 check_added_monitors!(nodes[1], 1);
4211 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4212 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4213 assert_eq!(node_txn.len(), 1);
4214 check_spends!(node_txn[0], chan.3);
4215 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
4217 mine_transaction(&nodes[1], &node_txn[0]);
4218 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4220 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4221 assert_eq!(spend_txn.len(), 1);
4222 assert_eq!(spend_txn[0].input.len(), 1);
4223 check_spends!(spend_txn[0], node_txn[0]);
4224 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4228 fn test_claim_on_remote_sizeable_push_msat() {
4229 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4230 // to_remote output is encumbered by a P2WPKH
4231 let chanmon_cfgs = create_chanmon_cfgs(2);
4232 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4233 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4234 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4236 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());
4237 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4238 check_closed_broadcast!(nodes[0], true);
4239 check_added_monitors!(nodes[0], 1);
4240 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4242 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4243 assert_eq!(node_txn.len(), 1);
4244 check_spends!(node_txn[0], chan.3);
4245 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
4247 mine_transaction(&nodes[1], &node_txn[0]);
4248 check_closed_broadcast!(nodes[1], true);
4249 check_added_monitors!(nodes[1], 1);
4250 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4251 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4253 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4254 assert_eq!(spend_txn.len(), 1);
4255 check_spends!(spend_txn[0], node_txn[0]);
4259 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4260 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4261 // to_remote output is encumbered by a P2WPKH
4263 let chanmon_cfgs = create_chanmon_cfgs(2);
4264 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4265 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4266 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4268 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4269 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4270 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4271 assert_eq!(revoked_local_txn[0].input.len(), 1);
4272 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4274 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4275 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4276 check_closed_broadcast!(nodes[1], true);
4277 check_added_monitors!(nodes[1], 1);
4278 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4280 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4281 mine_transaction(&nodes[1], &node_txn[0]);
4282 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4284 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4285 assert_eq!(spend_txn.len(), 3);
4286 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4287 check_spends!(spend_txn[1], node_txn[0]);
4288 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4292 fn test_static_spendable_outputs_preimage_tx() {
4293 let chanmon_cfgs = create_chanmon_cfgs(2);
4294 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4295 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4296 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4298 // Create some initial channels
4299 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4301 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4303 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4304 assert_eq!(commitment_tx[0].input.len(), 1);
4305 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4307 // Settle A's commitment tx on B's chain
4308 nodes[1].node.claim_funds(payment_preimage);
4309 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4310 check_added_monitors!(nodes[1], 1);
4311 mine_transaction(&nodes[1], &commitment_tx[0]);
4312 check_added_monitors!(nodes[1], 1);
4313 let events = nodes[1].node.get_and_clear_pending_msg_events();
4315 MessageSendEvent::UpdateHTLCs { .. } => {},
4316 _ => panic!("Unexpected event"),
4319 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4320 _ => panic!("Unexepected event"),
4323 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4324 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4325 assert_eq!(node_txn.len(), 3);
4326 check_spends!(node_txn[0], commitment_tx[0]);
4327 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4328 check_spends!(node_txn[1], chan_1.3);
4329 check_spends!(node_txn[2], node_txn[1]);
4331 mine_transaction(&nodes[1], &node_txn[0]);
4332 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4333 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4335 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4336 assert_eq!(spend_txn.len(), 1);
4337 check_spends!(spend_txn[0], node_txn[0]);
4341 fn test_static_spendable_outputs_timeout_tx() {
4342 let chanmon_cfgs = create_chanmon_cfgs(2);
4343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4345 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4347 // Create some initial channels
4348 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4350 // Rebalance the network a bit by relaying one payment through all the channels ...
4351 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4353 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4355 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4356 assert_eq!(commitment_tx[0].input.len(), 1);
4357 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4359 // Settle A's commitment tx on B' chain
4360 mine_transaction(&nodes[1], &commitment_tx[0]);
4361 check_added_monitors!(nodes[1], 1);
4362 let events = nodes[1].node.get_and_clear_pending_msg_events();
4364 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4365 _ => panic!("Unexpected event"),
4367 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4369 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4370 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4371 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4372 check_spends!(node_txn[0], chan_1.3.clone());
4373 check_spends!(node_txn[1], commitment_tx[0].clone());
4374 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4376 mine_transaction(&nodes[1], &node_txn[1]);
4377 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4378 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4379 expect_payment_failed!(nodes[1], our_payment_hash, false);
4381 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4382 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4383 check_spends!(spend_txn[0], commitment_tx[0]);
4384 check_spends!(spend_txn[1], node_txn[1]);
4385 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4389 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4390 let chanmon_cfgs = create_chanmon_cfgs(2);
4391 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4392 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4393 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4395 // Create some initial channels
4396 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4398 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4399 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4400 assert_eq!(revoked_local_txn[0].input.len(), 1);
4401 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4403 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4405 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4406 check_closed_broadcast!(nodes[1], true);
4407 check_added_monitors!(nodes[1], 1);
4408 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4410 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4411 assert_eq!(node_txn.len(), 2);
4412 assert_eq!(node_txn[0].input.len(), 2);
4413 check_spends!(node_txn[0], revoked_local_txn[0]);
4415 mine_transaction(&nodes[1], &node_txn[0]);
4416 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4418 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4419 assert_eq!(spend_txn.len(), 1);
4420 check_spends!(spend_txn[0], node_txn[0]);
4424 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4425 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4426 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4429 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4431 // Create some initial channels
4432 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4434 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4435 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4436 assert_eq!(revoked_local_txn[0].input.len(), 1);
4437 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4439 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4441 // A will generate HTLC-Timeout from revoked commitment tx
4442 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4443 check_closed_broadcast!(nodes[0], true);
4444 check_added_monitors!(nodes[0], 1);
4445 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4446 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4448 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4449 assert_eq!(revoked_htlc_txn.len(), 2);
4450 check_spends!(revoked_htlc_txn[0], chan_1.3);
4451 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4452 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4453 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4454 assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
4456 // B will generate justice tx from A's revoked commitment/HTLC tx
4457 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4458 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4459 check_closed_broadcast!(nodes[1], true);
4460 check_added_monitors!(nodes[1], 1);
4461 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4463 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4464 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4465 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4466 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4467 // transactions next...
4468 assert_eq!(node_txn[0].input.len(), 3);
4469 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4471 assert_eq!(node_txn[1].input.len(), 2);
4472 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4473 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4474 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4476 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4477 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4480 assert_eq!(node_txn[2].input.len(), 1);
4481 check_spends!(node_txn[2], chan_1.3);
4483 mine_transaction(&nodes[1], &node_txn[1]);
4484 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4486 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4487 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4488 assert_eq!(spend_txn.len(), 1);
4489 assert_eq!(spend_txn[0].input.len(), 1);
4490 check_spends!(spend_txn[0], node_txn[1]);
4494 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4495 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4496 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4499 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4501 // Create some initial channels
4502 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4504 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4505 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4506 assert_eq!(revoked_local_txn[0].input.len(), 1);
4507 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4509 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4510 assert_eq!(revoked_local_txn[0].output.len(), 2);
4512 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4514 // B will generate HTLC-Success from revoked commitment tx
4515 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4516 check_closed_broadcast!(nodes[1], true);
4517 check_added_monitors!(nodes[1], 1);
4518 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4519 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4521 assert_eq!(revoked_htlc_txn.len(), 2);
4522 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4523 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4524 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4526 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4527 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4528 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4530 // A will generate justice tx from B's revoked commitment/HTLC tx
4531 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4532 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4533 check_closed_broadcast!(nodes[0], true);
4534 check_added_monitors!(nodes[0], 1);
4535 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4537 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4538 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4540 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4541 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4542 // transactions next...
4543 assert_eq!(node_txn[0].input.len(), 2);
4544 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4545 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4546 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4548 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4549 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4552 assert_eq!(node_txn[1].input.len(), 1);
4553 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4555 check_spends!(node_txn[2], chan_1.3);
4557 mine_transaction(&nodes[0], &node_txn[1]);
4558 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4560 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4561 // didn't try to generate any new transactions.
4563 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4564 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4565 assert_eq!(spend_txn.len(), 3);
4566 assert_eq!(spend_txn[0].input.len(), 1);
4567 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4568 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4569 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4570 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4574 fn test_onchain_to_onchain_claim() {
4575 // Test that in case of channel closure, we detect the state of output and claim HTLC
4576 // on downstream peer's remote commitment tx.
4577 // First, have C claim an HTLC against its own latest commitment transaction.
4578 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4580 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4583 let chanmon_cfgs = create_chanmon_cfgs(3);
4584 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4585 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4586 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4588 // Create some initial channels
4589 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4590 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4592 // Ensure all nodes are at the same height
4593 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4594 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4595 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4596 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4598 // Rebalance the network a bit by relaying one payment through all the channels ...
4599 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4600 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4602 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4603 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4604 check_spends!(commitment_tx[0], chan_2.3);
4605 nodes[2].node.claim_funds(payment_preimage);
4606 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4607 check_added_monitors!(nodes[2], 1);
4608 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4609 assert!(updates.update_add_htlcs.is_empty());
4610 assert!(updates.update_fail_htlcs.is_empty());
4611 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4612 assert!(updates.update_fail_malformed_htlcs.is_empty());
4614 mine_transaction(&nodes[2], &commitment_tx[0]);
4615 check_closed_broadcast!(nodes[2], true);
4616 check_added_monitors!(nodes[2], 1);
4617 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4619 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4620 assert_eq!(c_txn.len(), 3);
4621 assert_eq!(c_txn[0], c_txn[2]);
4622 assert_eq!(commitment_tx[0], c_txn[1]);
4623 check_spends!(c_txn[1], chan_2.3);
4624 check_spends!(c_txn[2], c_txn[1]);
4625 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4626 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4627 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4628 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4630 // 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
4631 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4632 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4633 check_added_monitors!(nodes[1], 1);
4634 let events = nodes[1].node.get_and_clear_pending_events();
4635 assert_eq!(events.len(), 2);
4637 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4638 _ => panic!("Unexpected event"),
4641 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4642 assert_eq!(fee_earned_msat, Some(1000));
4643 assert_eq!(prev_channel_id, Some(chan_1.2));
4644 assert_eq!(claim_from_onchain_tx, true);
4645 assert_eq!(next_channel_id, Some(chan_2.2));
4647 _ => panic!("Unexpected event"),
4650 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4651 // ChannelMonitor: claim tx
4652 assert_eq!(b_txn.len(), 1);
4653 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
4656 check_added_monitors!(nodes[1], 1);
4657 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4658 assert_eq!(msg_events.len(), 3);
4659 match msg_events[0] {
4660 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4661 _ => panic!("Unexpected event"),
4663 match msg_events[1] {
4664 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4665 _ => panic!("Unexpected event"),
4667 match msg_events[2] {
4668 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, .. } } => {
4669 assert!(update_add_htlcs.is_empty());
4670 assert!(update_fail_htlcs.is_empty());
4671 assert_eq!(update_fulfill_htlcs.len(), 1);
4672 assert!(update_fail_malformed_htlcs.is_empty());
4673 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4675 _ => panic!("Unexpected event"),
4677 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4678 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4679 mine_transaction(&nodes[1], &commitment_tx[0]);
4680 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4681 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4682 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4683 assert_eq!(b_txn.len(), 3);
4684 check_spends!(b_txn[1], chan_1.3);
4685 check_spends!(b_txn[2], b_txn[1]);
4686 check_spends!(b_txn[0], commitment_tx[0]);
4687 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4688 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4689 assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
4691 check_closed_broadcast!(nodes[1], true);
4692 check_added_monitors!(nodes[1], 1);
4696 fn test_duplicate_payment_hash_one_failure_one_success() {
4697 // Topology : A --> B --> C --> D
4698 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4699 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4700 // we forward one of the payments onwards to D.
4701 let chanmon_cfgs = create_chanmon_cfgs(4);
4702 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4703 // When this test was written, the default base fee floated based on the HTLC count.
4704 // It is now fixed, so we simply set the fee to the expected value here.
4705 let mut config = test_default_channel_config();
4706 config.channel_config.forwarding_fee_base_msat = 196;
4707 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4708 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4709 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4711 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4712 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4713 create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4715 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4716 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4717 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4718 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4719 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4721 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4723 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
4724 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4725 // script push size limit so that the below script length checks match
4726 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4727 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
4728 .with_features(channelmanager::provided_invoice_features());
4729 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
4730 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
4732 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4733 assert_eq!(commitment_txn[0].input.len(), 1);
4734 check_spends!(commitment_txn[0], chan_2.3);
4736 mine_transaction(&nodes[1], &commitment_txn[0]);
4737 check_closed_broadcast!(nodes[1], true);
4738 check_added_monitors!(nodes[1], 1);
4739 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4740 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4742 let htlc_timeout_tx;
4743 { // Extract one of the two HTLC-Timeout transaction
4744 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4745 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
4746 assert!(node_txn.len() == 4 || node_txn.len() == 3);
4747 check_spends!(node_txn[0], chan_2.3);
4749 check_spends!(node_txn[1], commitment_txn[0]);
4750 assert_eq!(node_txn[1].input.len(), 1);
4752 if node_txn.len() > 3 {
4753 check_spends!(node_txn[2], commitment_txn[0]);
4754 assert_eq!(node_txn[2].input.len(), 1);
4755 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
4757 check_spends!(node_txn[3], commitment_txn[0]);
4758 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
4760 check_spends!(node_txn[2], commitment_txn[0]);
4761 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
4764 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4765 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4766 if node_txn.len() > 3 {
4767 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4769 htlc_timeout_tx = node_txn[1].clone();
4772 nodes[2].node.claim_funds(our_payment_preimage);
4773 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4775 mine_transaction(&nodes[2], &commitment_txn[0]);
4776 check_added_monitors!(nodes[2], 2);
4777 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4778 let events = nodes[2].node.get_and_clear_pending_msg_events();
4780 MessageSendEvent::UpdateHTLCs { .. } => {},
4781 _ => panic!("Unexpected event"),
4784 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4785 _ => panic!("Unexepected event"),
4787 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4788 assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
4789 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4790 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4791 assert_eq!(htlc_success_txn[0].input.len(), 1);
4792 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4793 assert_eq!(htlc_success_txn[1].input.len(), 1);
4794 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4795 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4796 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
4797 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
4798 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
4799 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4801 mine_transaction(&nodes[1], &htlc_timeout_tx);
4802 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4803 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 }]);
4804 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4805 assert!(htlc_updates.update_add_htlcs.is_empty());
4806 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4807 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4808 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4809 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4810 check_added_monitors!(nodes[1], 1);
4812 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4813 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4815 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4817 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4819 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4820 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
4821 // and nodes[2] fee) is rounded down and then claimed in full.
4822 mine_transaction(&nodes[1], &htlc_success_txn[0]);
4823 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
4824 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4825 assert!(updates.update_add_htlcs.is_empty());
4826 assert!(updates.update_fail_htlcs.is_empty());
4827 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4828 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4829 assert!(updates.update_fail_malformed_htlcs.is_empty());
4830 check_added_monitors!(nodes[1], 1);
4832 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4833 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4835 let events = nodes[0].node.get_and_clear_pending_events();
4837 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4838 assert_eq!(*payment_preimage, our_payment_preimage);
4839 assert_eq!(*payment_hash, duplicate_payment_hash);
4841 _ => panic!("Unexpected event"),
4846 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4847 let chanmon_cfgs = create_chanmon_cfgs(2);
4848 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4849 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4850 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4852 // Create some initial channels
4853 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4855 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4856 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4857 assert_eq!(local_txn.len(), 1);
4858 assert_eq!(local_txn[0].input.len(), 1);
4859 check_spends!(local_txn[0], chan_1.3);
4861 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4862 nodes[1].node.claim_funds(payment_preimage);
4863 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4864 check_added_monitors!(nodes[1], 1);
4866 mine_transaction(&nodes[1], &local_txn[0]);
4867 check_added_monitors!(nodes[1], 1);
4868 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4869 let events = nodes[1].node.get_and_clear_pending_msg_events();
4871 MessageSendEvent::UpdateHTLCs { .. } => {},
4872 _ => panic!("Unexpected event"),
4875 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4876 _ => panic!("Unexepected event"),
4879 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4880 assert_eq!(node_txn.len(), 3);
4881 assert_eq!(node_txn[0], node_txn[2]);
4882 assert_eq!(node_txn[1], local_txn[0]);
4883 assert_eq!(node_txn[0].input.len(), 1);
4884 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4885 check_spends!(node_txn[0], local_txn[0]);
4889 mine_transaction(&nodes[1], &node_tx);
4890 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4892 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4893 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4894 assert_eq!(spend_txn.len(), 1);
4895 assert_eq!(spend_txn[0].input.len(), 1);
4896 check_spends!(spend_txn[0], node_tx);
4897 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4900 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4901 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4902 // unrevoked commitment transaction.
4903 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4904 // a remote RAA before they could be failed backwards (and combinations thereof).
4905 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4906 // use the same payment hashes.
4907 // Thus, we use a six-node network:
4912 // And test where C fails back to A/B when D announces its latest commitment transaction
4913 let chanmon_cfgs = create_chanmon_cfgs(6);
4914 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4915 // When this test was written, the default base fee floated based on the HTLC count.
4916 // It is now fixed, so we simply set the fee to the expected value here.
4917 let mut config = test_default_channel_config();
4918 config.channel_config.forwarding_fee_base_msat = 196;
4919 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4920 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4921 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4923 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4924 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4925 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4926 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4927 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4929 // Rebalance and check output sanity...
4930 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4931 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4932 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4934 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4936 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
4938 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
4939 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4941 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
4943 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
4945 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4947 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4948 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4950 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());
4952 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());
4955 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4957 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4958 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
4961 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
4963 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4964 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());
4966 // Double-check that six of the new HTLC were added
4967 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4968 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4969 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4970 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4972 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4973 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4974 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4975 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4976 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4977 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4978 check_added_monitors!(nodes[4], 0);
4980 let failed_destinations = vec![
4981 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4982 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4983 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
4984 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
4986 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
4987 check_added_monitors!(nodes[4], 1);
4989 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4990 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4991 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4992 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4993 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4994 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4996 // Fail 3rd below-dust and 7th above-dust HTLCs
4997 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
4998 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
4999 check_added_monitors!(nodes[5], 0);
5001 let failed_destinations_2 = vec![
5002 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5003 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5005 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5006 check_added_monitors!(nodes[5], 1);
5008 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5009 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5010 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5011 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5013 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5015 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5016 let failed_destinations_3 = vec![
5017 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5018 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5019 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5020 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5021 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5022 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5024 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5025 check_added_monitors!(nodes[3], 1);
5026 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5027 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5028 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5029 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5030 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5031 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5032 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5033 if deliver_last_raa {
5034 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5036 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5039 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5040 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5041 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5042 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5044 // We now broadcast the latest commitment transaction, which *should* result in failures for
5045 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5046 // the non-broadcast above-dust HTLCs.
5048 // Alternatively, we may broadcast the previous commitment transaction, which should only
5049 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5050 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5052 if announce_latest {
5053 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5055 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5057 let events = nodes[2].node.get_and_clear_pending_events();
5058 let close_event = if deliver_last_raa {
5059 assert_eq!(events.len(), 2 + 6);
5060 events.last().clone().unwrap()
5062 assert_eq!(events.len(), 1);
5063 events.last().clone().unwrap()
5066 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5067 _ => panic!("Unexpected event"),
5070 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5071 check_closed_broadcast!(nodes[2], true);
5072 if deliver_last_raa {
5073 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5075 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();
5076 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5078 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5079 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5081 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5084 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5086 check_added_monitors!(nodes[2], 3);
5088 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5089 assert_eq!(cs_msgs.len(), 2);
5090 let mut a_done = false;
5091 for msg in cs_msgs {
5093 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5094 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5095 // should be failed-backwards here.
5096 let target = if *node_id == nodes[0].node.get_our_node_id() {
5097 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5098 for htlc in &updates.update_fail_htlcs {
5099 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 });
5101 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5106 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5107 for htlc in &updates.update_fail_htlcs {
5108 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5110 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5111 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5114 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5115 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5116 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5117 if announce_latest {
5118 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5119 if *node_id == nodes[0].node.get_our_node_id() {
5120 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5123 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5125 _ => panic!("Unexpected event"),
5129 let as_events = nodes[0].node.get_and_clear_pending_events();
5130 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5131 let mut as_failds = HashSet::new();
5132 let mut as_updates = 0;
5133 for event in as_events.iter() {
5134 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5135 assert!(as_failds.insert(*payment_hash));
5136 if *payment_hash != payment_hash_2 {
5137 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5139 assert!(!payment_failed_permanently);
5141 if network_update.is_some() {
5144 } else { panic!("Unexpected event"); }
5146 assert!(as_failds.contains(&payment_hash_1));
5147 assert!(as_failds.contains(&payment_hash_2));
5148 if announce_latest {
5149 assert!(as_failds.contains(&payment_hash_3));
5150 assert!(as_failds.contains(&payment_hash_5));
5152 assert!(as_failds.contains(&payment_hash_6));
5154 let bs_events = nodes[1].node.get_and_clear_pending_events();
5155 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5156 let mut bs_failds = HashSet::new();
5157 let mut bs_updates = 0;
5158 for event in bs_events.iter() {
5159 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5160 assert!(bs_failds.insert(*payment_hash));
5161 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5162 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5164 assert!(!payment_failed_permanently);
5166 if network_update.is_some() {
5169 } else { panic!("Unexpected event"); }
5171 assert!(bs_failds.contains(&payment_hash_1));
5172 assert!(bs_failds.contains(&payment_hash_2));
5173 if announce_latest {
5174 assert!(bs_failds.contains(&payment_hash_4));
5176 assert!(bs_failds.contains(&payment_hash_5));
5178 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5179 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5180 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5181 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5182 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5183 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5187 fn test_fail_backwards_latest_remote_announce_a() {
5188 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5192 fn test_fail_backwards_latest_remote_announce_b() {
5193 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5197 fn test_fail_backwards_previous_remote_announce() {
5198 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5199 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5200 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5204 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5205 let chanmon_cfgs = create_chanmon_cfgs(2);
5206 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5207 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5208 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5210 // Create some initial channels
5211 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5213 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5214 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5215 assert_eq!(local_txn[0].input.len(), 1);
5216 check_spends!(local_txn[0], chan_1.3);
5218 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5219 mine_transaction(&nodes[0], &local_txn[0]);
5220 check_closed_broadcast!(nodes[0], true);
5221 check_added_monitors!(nodes[0], 1);
5222 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5223 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5225 let htlc_timeout = {
5226 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5227 assert_eq!(node_txn.len(), 2);
5228 check_spends!(node_txn[0], chan_1.3);
5229 assert_eq!(node_txn[1].input.len(), 1);
5230 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5231 check_spends!(node_txn[1], local_txn[0]);
5235 mine_transaction(&nodes[0], &htlc_timeout);
5236 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5237 expect_payment_failed!(nodes[0], our_payment_hash, false);
5239 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5240 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5241 assert_eq!(spend_txn.len(), 3);
5242 check_spends!(spend_txn[0], local_txn[0]);
5243 assert_eq!(spend_txn[1].input.len(), 1);
5244 check_spends!(spend_txn[1], htlc_timeout);
5245 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5246 assert_eq!(spend_txn[2].input.len(), 2);
5247 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5248 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5249 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5253 fn test_key_derivation_params() {
5254 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5255 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5256 // let us re-derive the channel key set to then derive a delayed_payment_key.
5258 let chanmon_cfgs = create_chanmon_cfgs(3);
5260 // We manually create the node configuration to backup the seed.
5261 let seed = [42; 32];
5262 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5263 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);
5264 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5265 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, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, features: channelmanager::provided_init_features() };
5266 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5267 node_cfgs.remove(0);
5268 node_cfgs.insert(0, node);
5270 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5271 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5273 // Create some initial channels
5274 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5276 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5277 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5278 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5280 // Ensure all nodes are at the same height
5281 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5282 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5283 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5284 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5286 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5287 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5288 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5289 assert_eq!(local_txn_1[0].input.len(), 1);
5290 check_spends!(local_txn_1[0], chan_1.3);
5292 // We check funding pubkey are unique
5293 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]));
5294 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]));
5295 if from_0_funding_key_0 == from_1_funding_key_0
5296 || from_0_funding_key_0 == from_1_funding_key_1
5297 || from_0_funding_key_1 == from_1_funding_key_0
5298 || from_0_funding_key_1 == from_1_funding_key_1 {
5299 panic!("Funding pubkeys aren't unique");
5302 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5303 mine_transaction(&nodes[0], &local_txn_1[0]);
5304 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5305 check_closed_broadcast!(nodes[0], true);
5306 check_added_monitors!(nodes[0], 1);
5307 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5309 let htlc_timeout = {
5310 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5311 assert_eq!(node_txn[1].input.len(), 1);
5312 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5313 check_spends!(node_txn[1], local_txn_1[0]);
5317 mine_transaction(&nodes[0], &htlc_timeout);
5318 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5319 expect_payment_failed!(nodes[0], our_payment_hash, false);
5321 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5322 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5323 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5324 assert_eq!(spend_txn.len(), 3);
5325 check_spends!(spend_txn[0], local_txn_1[0]);
5326 assert_eq!(spend_txn[1].input.len(), 1);
5327 check_spends!(spend_txn[1], htlc_timeout);
5328 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5329 assert_eq!(spend_txn[2].input.len(), 2);
5330 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5331 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5332 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5336 fn test_static_output_closing_tx() {
5337 let chanmon_cfgs = create_chanmon_cfgs(2);
5338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5340 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5342 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5344 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5345 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5347 mine_transaction(&nodes[0], &closing_tx);
5348 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5349 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5351 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5352 assert_eq!(spend_txn.len(), 1);
5353 check_spends!(spend_txn[0], closing_tx);
5355 mine_transaction(&nodes[1], &closing_tx);
5356 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5357 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5359 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5360 assert_eq!(spend_txn.len(), 1);
5361 check_spends!(spend_txn[0], closing_tx);
5364 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5365 let chanmon_cfgs = create_chanmon_cfgs(2);
5366 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5367 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5368 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5369 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5371 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5373 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5374 // present in B's local commitment transaction, but none of A's commitment transactions.
5375 nodes[1].node.claim_funds(payment_preimage);
5376 check_added_monitors!(nodes[1], 1);
5377 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5379 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5380 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5381 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5383 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5384 check_added_monitors!(nodes[0], 1);
5385 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5386 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5387 check_added_monitors!(nodes[1], 1);
5389 let starting_block = nodes[1].best_block_info();
5390 let mut block = Block {
5391 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5394 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5395 connect_block(&nodes[1], &block);
5396 block.header.prev_blockhash = block.block_hash();
5398 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5399 check_closed_broadcast!(nodes[1], true);
5400 check_added_monitors!(nodes[1], 1);
5401 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5404 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5405 let chanmon_cfgs = create_chanmon_cfgs(2);
5406 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5407 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5408 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5409 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5411 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5412 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5413 check_added_monitors!(nodes[0], 1);
5415 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5417 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5418 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5419 // to "time out" the HTLC.
5421 let starting_block = nodes[1].best_block_info();
5422 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5424 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5425 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5426 header.prev_blockhash = header.block_hash();
5428 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5429 check_closed_broadcast!(nodes[0], true);
5430 check_added_monitors!(nodes[0], 1);
5431 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5434 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5435 let chanmon_cfgs = create_chanmon_cfgs(3);
5436 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5437 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5438 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5439 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5441 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5442 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5443 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5444 // actually revoked.
5445 let htlc_value = if use_dust { 50000 } else { 3000000 };
5446 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5447 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5448 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5449 check_added_monitors!(nodes[1], 1);
5451 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5452 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5453 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5454 check_added_monitors!(nodes[0], 1);
5455 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5456 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5457 check_added_monitors!(nodes[1], 1);
5458 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5459 check_added_monitors!(nodes[1], 1);
5460 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5462 if check_revoke_no_close {
5463 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5464 check_added_monitors!(nodes[0], 1);
5467 let starting_block = nodes[1].best_block_info();
5468 let mut block = Block {
5469 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5472 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5473 connect_block(&nodes[0], &block);
5474 block.header.prev_blockhash = block.block_hash();
5476 if !check_revoke_no_close {
5477 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5478 check_closed_broadcast!(nodes[0], true);
5479 check_added_monitors!(nodes[0], 1);
5480 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5482 expect_payment_failed!(nodes[0], our_payment_hash, true);
5486 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5487 // There are only a few cases to test here:
5488 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5489 // broadcastable commitment transactions result in channel closure,
5490 // * its included in an unrevoked-but-previous remote commitment transaction,
5491 // * its included in the latest remote or local commitment transactions.
5492 // We test each of the three possible commitment transactions individually and use both dust and
5494 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5495 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5496 // tested for at least one of the cases in other tests.
5498 fn htlc_claim_single_commitment_only_a() {
5499 do_htlc_claim_local_commitment_only(true);
5500 do_htlc_claim_local_commitment_only(false);
5502 do_htlc_claim_current_remote_commitment_only(true);
5503 do_htlc_claim_current_remote_commitment_only(false);
5507 fn htlc_claim_single_commitment_only_b() {
5508 do_htlc_claim_previous_remote_commitment_only(true, false);
5509 do_htlc_claim_previous_remote_commitment_only(false, false);
5510 do_htlc_claim_previous_remote_commitment_only(true, true);
5511 do_htlc_claim_previous_remote_commitment_only(false, true);
5516 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5517 let chanmon_cfgs = create_chanmon_cfgs(2);
5518 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5519 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5520 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5521 // Force duplicate randomness for every get-random call
5522 for node in nodes.iter() {
5523 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5526 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5527 let channel_value_satoshis=10000;
5528 let push_msat=10001;
5529 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5530 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5531 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5532 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5534 // Create a second channel with the same random values. This used to panic due to a colliding
5535 // channel_id, but now panics due to a colliding outbound SCID alias.
5536 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5540 fn bolt2_open_channel_sending_node_checks_part2() {
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 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5547 let channel_value_satoshis=2^24;
5548 let push_msat=10001;
5549 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5551 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5552 let channel_value_satoshis=10000;
5553 // Test when push_msat is equal to 1000 * funding_satoshis.
5554 let push_msat=1000*channel_value_satoshis+1;
5555 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5557 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5558 let channel_value_satoshis=10000;
5559 let push_msat=10001;
5560 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
5561 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5562 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5564 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5565 // 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
5566 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5568 // 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.
5569 assert!(BREAKDOWN_TIMEOUT>0);
5570 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5572 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5573 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5574 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5576 // 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.
5577 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5578 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5579 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5580 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5581 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5585 fn bolt2_open_channel_sane_dust_limit() {
5586 let chanmon_cfgs = create_chanmon_cfgs(2);
5587 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5588 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5589 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5591 let channel_value_satoshis=1000000;
5592 let push_msat=10001;
5593 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5594 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5595 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5596 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5598 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5599 let events = nodes[1].node.get_and_clear_pending_msg_events();
5600 let err_msg = match events[0] {
5601 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5604 _ => panic!("Unexpected event"),
5606 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5609 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5610 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5611 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5612 // is no longer affordable once it's freed.
5614 fn test_fail_holding_cell_htlc_upon_free() {
5615 let chanmon_cfgs = create_chanmon_cfgs(2);
5616 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5617 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5618 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5619 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5621 // First nodes[0] generates an update_fee, setting the channel's
5622 // pending_update_fee.
5624 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5625 *feerate_lock += 20;
5627 nodes[0].node.timer_tick_occurred();
5628 check_added_monitors!(nodes[0], 1);
5630 let events = nodes[0].node.get_and_clear_pending_msg_events();
5631 assert_eq!(events.len(), 1);
5632 let (update_msg, commitment_signed) = match events[0] {
5633 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5634 (update_fee.as_ref(), commitment_signed)
5636 _ => panic!("Unexpected event"),
5639 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5641 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5642 let channel_reserve = chan_stat.channel_reserve_msat;
5643 let feerate = get_feerate!(nodes[0], chan.2);
5644 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
5646 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5647 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5648 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5650 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5651 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5652 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5653 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5655 // Flush the pending fee update.
5656 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5657 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5658 check_added_monitors!(nodes[1], 1);
5659 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5660 check_added_monitors!(nodes[0], 1);
5662 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5663 // HTLC, but now that the fee has been raised the payment will now fail, causing
5664 // us to surface its failure to the user.
5665 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5666 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5667 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);
5668 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 {}",
5669 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5670 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5672 // Check that the payment failed to be sent out.
5673 let events = nodes[0].node.get_and_clear_pending_events();
5674 assert_eq!(events.len(), 1);
5676 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5677 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5678 assert_eq!(our_payment_hash.clone(), *payment_hash);
5679 assert_eq!(*payment_failed_permanently, false);
5680 assert_eq!(*all_paths_failed, true);
5681 assert_eq!(*network_update, None);
5682 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5684 _ => panic!("Unexpected event"),
5688 // Test that if multiple HTLCs are released from the holding cell and one is
5689 // valid but the other is no longer valid upon release, the valid HTLC can be
5690 // successfully completed while the other one fails as expected.
5692 fn test_free_and_fail_holding_cell_htlcs() {
5693 let chanmon_cfgs = create_chanmon_cfgs(2);
5694 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5695 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5696 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5697 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5699 // First nodes[0] generates an update_fee, setting the channel's
5700 // pending_update_fee.
5702 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5703 *feerate_lock += 200;
5705 nodes[0].node.timer_tick_occurred();
5706 check_added_monitors!(nodes[0], 1);
5708 let events = nodes[0].node.get_and_clear_pending_msg_events();
5709 assert_eq!(events.len(), 1);
5710 let (update_msg, commitment_signed) = match events[0] {
5711 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5712 (update_fee.as_ref(), commitment_signed)
5714 _ => panic!("Unexpected event"),
5717 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5719 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5720 let channel_reserve = chan_stat.channel_reserve_msat;
5721 let feerate = get_feerate!(nodes[0], chan.2);
5722 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
5724 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5726 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5727 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5728 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5730 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5731 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5732 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5733 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5734 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5735 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5736 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5737 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5739 // Flush the pending fee update.
5740 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5741 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5742 check_added_monitors!(nodes[1], 1);
5743 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5744 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5745 check_added_monitors!(nodes[0], 2);
5747 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5748 // but now that the fee has been raised the second payment will now fail, causing us
5749 // to surface its failure to the user. The first payment should succeed.
5750 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5751 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5752 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);
5753 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 {}",
5754 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5755 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5757 // Check that the second payment failed to be sent out.
5758 let events = nodes[0].node.get_and_clear_pending_events();
5759 assert_eq!(events.len(), 1);
5761 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5762 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5763 assert_eq!(payment_hash_2.clone(), *payment_hash);
5764 assert_eq!(*payment_failed_permanently, false);
5765 assert_eq!(*all_paths_failed, true);
5766 assert_eq!(*network_update, None);
5767 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5769 _ => panic!("Unexpected event"),
5772 // Complete the first payment and the RAA from the fee update.
5773 let (payment_event, send_raa_event) = {
5774 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5775 assert_eq!(msgs.len(), 2);
5776 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5778 let raa = match send_raa_event {
5779 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5780 _ => panic!("Unexpected event"),
5782 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5783 check_added_monitors!(nodes[1], 1);
5784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5785 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5786 let events = nodes[1].node.get_and_clear_pending_events();
5787 assert_eq!(events.len(), 1);
5789 Event::PendingHTLCsForwardable { .. } => {},
5790 _ => panic!("Unexpected event"),
5792 nodes[1].node.process_pending_htlc_forwards();
5793 let events = nodes[1].node.get_and_clear_pending_events();
5794 assert_eq!(events.len(), 1);
5796 Event::PaymentReceived { .. } => {},
5797 _ => panic!("Unexpected event"),
5799 nodes[1].node.claim_funds(payment_preimage_1);
5800 check_added_monitors!(nodes[1], 1);
5801 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5803 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5804 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5805 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5806 expect_payment_sent!(nodes[0], payment_preimage_1);
5809 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5810 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5811 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5814 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5815 let chanmon_cfgs = create_chanmon_cfgs(3);
5816 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5817 // When this test was written, the default base fee floated based on the HTLC count.
5818 // It is now fixed, so we simply set the fee to the expected value here.
5819 let mut config = test_default_channel_config();
5820 config.channel_config.forwarding_fee_base_msat = 196;
5821 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5822 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5823 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5824 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5826 // First nodes[1] generates an update_fee, setting the channel's
5827 // pending_update_fee.
5829 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5830 *feerate_lock += 20;
5832 nodes[1].node.timer_tick_occurred();
5833 check_added_monitors!(nodes[1], 1);
5835 let events = nodes[1].node.get_and_clear_pending_msg_events();
5836 assert_eq!(events.len(), 1);
5837 let (update_msg, commitment_signed) = match events[0] {
5838 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5839 (update_fee.as_ref(), commitment_signed)
5841 _ => panic!("Unexpected event"),
5844 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5846 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
5847 let channel_reserve = chan_stat.channel_reserve_msat;
5848 let feerate = get_feerate!(nodes[0], chan_0_1.2);
5849 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
5851 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5853 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5854 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5855 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5856 let payment_event = {
5857 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5858 check_added_monitors!(nodes[0], 1);
5860 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5861 assert_eq!(events.len(), 1);
5863 SendEvent::from_event(events.remove(0))
5865 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5866 check_added_monitors!(nodes[1], 0);
5867 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5868 expect_pending_htlcs_forwardable!(nodes[1]);
5870 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
5871 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5873 // Flush the pending fee update.
5874 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5875 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5876 check_added_monitors!(nodes[2], 1);
5877 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5878 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5879 check_added_monitors!(nodes[1], 2);
5881 // A final RAA message is generated to finalize the fee update.
5882 let events = nodes[1].node.get_and_clear_pending_msg_events();
5883 assert_eq!(events.len(), 1);
5885 let raa_msg = match &events[0] {
5886 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5889 _ => panic!("Unexpected event"),
5892 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5893 check_added_monitors!(nodes[2], 1);
5894 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5896 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5897 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5898 assert_eq!(process_htlc_forwards_event.len(), 2);
5899 match &process_htlc_forwards_event[0] {
5900 &Event::PendingHTLCsForwardable { .. } => {},
5901 _ => panic!("Unexpected event"),
5904 // In response, we call ChannelManager's process_pending_htlc_forwards
5905 nodes[1].node.process_pending_htlc_forwards();
5906 check_added_monitors!(nodes[1], 1);
5908 // This causes the HTLC to be failed backwards.
5909 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5910 assert_eq!(fail_event.len(), 1);
5911 let (fail_msg, commitment_signed) = match &fail_event[0] {
5912 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5913 assert_eq!(updates.update_add_htlcs.len(), 0);
5914 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5915 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5916 assert_eq!(updates.update_fail_htlcs.len(), 1);
5917 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5919 _ => panic!("Unexpected event"),
5922 // Pass the failure messages back to nodes[0].
5923 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5924 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5926 // Complete the HTLC failure+removal process.
5927 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5928 check_added_monitors!(nodes[0], 1);
5929 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5930 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5931 check_added_monitors!(nodes[1], 2);
5932 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5933 assert_eq!(final_raa_event.len(), 1);
5934 let raa = match &final_raa_event[0] {
5935 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5936 _ => panic!("Unexpected event"),
5938 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5939 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5940 check_added_monitors!(nodes[0], 1);
5943 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5944 // 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.
5945 //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.
5948 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5949 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5950 let chanmon_cfgs = create_chanmon_cfgs(2);
5951 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5952 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5953 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5954 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5956 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5957 route.paths[0][0].fee_msat = 100;
5959 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 },
5960 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5961 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5962 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5966 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5967 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5968 let chanmon_cfgs = create_chanmon_cfgs(2);
5969 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5970 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5971 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5972 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5974 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5975 route.paths[0][0].fee_msat = 0;
5976 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 },
5977 assert_eq!(err, "Cannot send 0-msat HTLC"));
5979 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5980 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5984 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5985 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5986 let chanmon_cfgs = create_chanmon_cfgs(2);
5987 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5988 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5989 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5990 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5992 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
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);
5995 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5996 updates.update_add_htlcs[0].amount_msat = 0;
5998 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5999 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6000 check_closed_broadcast!(nodes[1], true).unwrap();
6001 check_added_monitors!(nodes[1], 1);
6002 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6006 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6007 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6008 //It is enforced when constructing a route.
6009 let chanmon_cfgs = create_chanmon_cfgs(2);
6010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6012 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6013 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6015 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6016 .with_features(channelmanager::provided_invoice_features());
6017 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6018 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6019 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::RouteError { ref err },
6020 assert_eq!(err, &"Channel CLTV overflowed?"));
6024 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6025 //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.
6026 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6027 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6028 let chanmon_cfgs = create_chanmon_cfgs(2);
6029 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6030 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6031 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6032 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6033 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6035 for i in 0..max_accepted_htlcs {
6036 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6037 let payment_event = {
6038 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6039 check_added_monitors!(nodes[0], 1);
6041 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6042 assert_eq!(events.len(), 1);
6043 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6044 assert_eq!(htlcs[0].htlc_id, i);
6048 SendEvent::from_event(events.remove(0))
6050 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6051 check_added_monitors!(nodes[1], 0);
6052 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6054 expect_pending_htlcs_forwardable!(nodes[1]);
6055 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6057 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6058 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 },
6059 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6061 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6062 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6066 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6067 //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.
6068 let chanmon_cfgs = create_chanmon_cfgs(2);
6069 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6070 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6071 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6072 let channel_value = 100000;
6073 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6074 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6076 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6078 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6079 // Manually create a route over our max in flight (which our router normally automatically
6081 route.paths[0][0].fee_msat = max_in_flight + 1;
6082 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 },
6083 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)));
6085 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6086 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);
6088 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6091 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6093 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6094 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6095 let chanmon_cfgs = create_chanmon_cfgs(2);
6096 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6097 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6098 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6099 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6100 let htlc_minimum_msat: u64;
6102 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6103 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6104 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6107 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6108 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6109 check_added_monitors!(nodes[0], 1);
6110 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6111 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6112 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6113 assert!(nodes[1].node.list_channels().is_empty());
6114 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6115 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()));
6116 check_added_monitors!(nodes[1], 1);
6117 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6121 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6122 //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
6123 let chanmon_cfgs = create_chanmon_cfgs(2);
6124 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6125 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6126 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6127 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6129 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6130 let channel_reserve = chan_stat.channel_reserve_msat;
6131 let feerate = get_feerate!(nodes[0], chan.2);
6132 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6133 // The 2* and +1 are for the fee spike reserve.
6134 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6136 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6137 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6138 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6139 check_added_monitors!(nodes[0], 1);
6140 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6142 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6143 // at this time channel-initiatee receivers are not required to enforce that senders
6144 // respect the fee_spike_reserve.
6145 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6146 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6148 assert!(nodes[1].node.list_channels().is_empty());
6149 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6150 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6151 check_added_monitors!(nodes[1], 1);
6152 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6156 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6157 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6158 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6159 let chanmon_cfgs = create_chanmon_cfgs(2);
6160 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6161 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6162 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6163 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6165 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6166 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6167 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6168 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6169 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6170 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6172 let mut msg = msgs::UpdateAddHTLC {
6176 payment_hash: our_payment_hash,
6177 cltv_expiry: htlc_cltv,
6178 onion_routing_packet: onion_packet.clone(),
6181 for i in 0..super::channel::OUR_MAX_HTLCS {
6182 msg.htlc_id = i as u64;
6183 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6185 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6186 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6188 assert!(nodes[1].node.list_channels().is_empty());
6189 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6190 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6191 check_added_monitors!(nodes[1], 1);
6192 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6196 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6197 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6198 let chanmon_cfgs = create_chanmon_cfgs(2);
6199 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6200 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6201 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6202 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6204 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6205 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6206 check_added_monitors!(nodes[0], 1);
6207 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6208 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6209 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6211 assert!(nodes[1].node.list_channels().is_empty());
6212 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6213 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6214 check_added_monitors!(nodes[1], 1);
6215 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6219 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6220 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6221 let chanmon_cfgs = create_chanmon_cfgs(2);
6222 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6223 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6224 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6226 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6227 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6228 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6229 check_added_monitors!(nodes[0], 1);
6230 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6231 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6232 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6234 assert!(nodes[1].node.list_channels().is_empty());
6235 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6236 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6237 check_added_monitors!(nodes[1], 1);
6238 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6242 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6243 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6244 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6245 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6246 let chanmon_cfgs = create_chanmon_cfgs(2);
6247 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6248 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6249 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6251 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6252 let (route, our_payment_hash, _, 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();
6254 check_added_monitors!(nodes[0], 1);
6255 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6256 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6258 //Disconnect and Reconnect
6259 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6260 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6261 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6262 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6263 assert_eq!(reestablish_1.len(), 1);
6264 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6265 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6266 assert_eq!(reestablish_2.len(), 1);
6267 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6268 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6269 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6270 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6273 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6274 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6275 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6276 check_added_monitors!(nodes[1], 1);
6277 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6279 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6281 assert!(nodes[1].node.list_channels().is_empty());
6282 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6283 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6284 check_added_monitors!(nodes[1], 1);
6285 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6289 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6290 //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.
6292 let chanmon_cfgs = create_chanmon_cfgs(2);
6293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6295 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6296 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6297 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6298 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6300 check_added_monitors!(nodes[0], 1);
6301 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6304 let update_msg = msgs::UpdateFulfillHTLC{
6307 payment_preimage: our_payment_preimage,
6310 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6312 assert!(nodes[0].node.list_channels().is_empty());
6313 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6314 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()));
6315 check_added_monitors!(nodes[0], 1);
6316 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6320 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6321 //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.
6323 let chanmon_cfgs = create_chanmon_cfgs(2);
6324 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6325 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6326 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6327 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6329 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6330 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6331 check_added_monitors!(nodes[0], 1);
6332 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6333 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6335 let update_msg = msgs::UpdateFailHTLC{
6338 reason: msgs::OnionErrorPacket { data: Vec::new()},
6341 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6343 assert!(nodes[0].node.list_channels().is_empty());
6344 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6345 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()));
6346 check_added_monitors!(nodes[0], 1);
6347 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6351 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6352 //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.
6354 let chanmon_cfgs = create_chanmon_cfgs(2);
6355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6357 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6358 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6360 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6361 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6362 check_added_monitors!(nodes[0], 1);
6363 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6364 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6365 let update_msg = msgs::UpdateFailMalformedHTLC{
6368 sha256_of_onion: [1; 32],
6369 failure_code: 0x8000,
6372 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6374 assert!(nodes[0].node.list_channels().is_empty());
6375 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6376 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()));
6377 check_added_monitors!(nodes[0], 1);
6378 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6382 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6383 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6385 let chanmon_cfgs = create_chanmon_cfgs(2);
6386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6389 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6391 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6393 nodes[1].node.claim_funds(our_payment_preimage);
6394 check_added_monitors!(nodes[1], 1);
6395 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6397 let events = nodes[1].node.get_and_clear_pending_msg_events();
6398 assert_eq!(events.len(), 1);
6399 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6401 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, .. } } => {
6402 assert!(update_add_htlcs.is_empty());
6403 assert_eq!(update_fulfill_htlcs.len(), 1);
6404 assert!(update_fail_htlcs.is_empty());
6405 assert!(update_fail_malformed_htlcs.is_empty());
6406 assert!(update_fee.is_none());
6407 update_fulfill_htlcs[0].clone()
6409 _ => panic!("Unexpected event"),
6413 update_fulfill_msg.htlc_id = 1;
6415 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6417 assert!(nodes[0].node.list_channels().is_empty());
6418 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6419 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6420 check_added_monitors!(nodes[0], 1);
6421 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6425 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6426 //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.
6428 let chanmon_cfgs = create_chanmon_cfgs(2);
6429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6431 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6432 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6434 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6436 nodes[1].node.claim_funds(our_payment_preimage);
6437 check_added_monitors!(nodes[1], 1);
6438 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6440 let events = nodes[1].node.get_and_clear_pending_msg_events();
6441 assert_eq!(events.len(), 1);
6442 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6444 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, .. } } => {
6445 assert!(update_add_htlcs.is_empty());
6446 assert_eq!(update_fulfill_htlcs.len(), 1);
6447 assert!(update_fail_htlcs.is_empty());
6448 assert!(update_fail_malformed_htlcs.is_empty());
6449 assert!(update_fee.is_none());
6450 update_fulfill_htlcs[0].clone()
6452 _ => panic!("Unexpected event"),
6456 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6458 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6460 assert!(nodes[0].node.list_channels().is_empty());
6461 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6462 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6463 check_added_monitors!(nodes[0], 1);
6464 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6468 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6469 //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.
6471 let chanmon_cfgs = create_chanmon_cfgs(2);
6472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6474 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6475 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6477 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6478 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6479 check_added_monitors!(nodes[0], 1);
6481 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6482 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6484 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6485 check_added_monitors!(nodes[1], 0);
6486 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6488 let events = nodes[1].node.get_and_clear_pending_msg_events();
6490 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6492 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, .. } } => {
6493 assert!(update_add_htlcs.is_empty());
6494 assert!(update_fulfill_htlcs.is_empty());
6495 assert!(update_fail_htlcs.is_empty());
6496 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6497 assert!(update_fee.is_none());
6498 update_fail_malformed_htlcs[0].clone()
6500 _ => panic!("Unexpected event"),
6503 update_msg.failure_code &= !0x8000;
6504 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6506 assert!(nodes[0].node.list_channels().is_empty());
6507 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6508 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6509 check_added_monitors!(nodes[0], 1);
6510 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6514 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6515 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6516 // * 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.
6518 let chanmon_cfgs = create_chanmon_cfgs(3);
6519 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6520 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6521 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6522 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6523 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6525 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6528 let mut payment_event = {
6529 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6530 check_added_monitors!(nodes[0], 1);
6531 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6532 assert_eq!(events.len(), 1);
6533 SendEvent::from_event(events.remove(0))
6535 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6536 check_added_monitors!(nodes[1], 0);
6537 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6538 expect_pending_htlcs_forwardable!(nodes[1]);
6539 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6540 assert_eq!(events_2.len(), 1);
6541 check_added_monitors!(nodes[1], 1);
6542 payment_event = SendEvent::from_event(events_2.remove(0));
6543 assert_eq!(payment_event.msgs.len(), 1);
6546 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6547 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6548 check_added_monitors!(nodes[2], 0);
6549 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6551 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6552 assert_eq!(events_3.len(), 1);
6553 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6555 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 } } => {
6556 assert!(update_add_htlcs.is_empty());
6557 assert!(update_fulfill_htlcs.is_empty());
6558 assert!(update_fail_htlcs.is_empty());
6559 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6560 assert!(update_fee.is_none());
6561 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6563 _ => panic!("Unexpected event"),
6567 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6569 check_added_monitors!(nodes[1], 0);
6570 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6571 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 }]);
6572 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6573 assert_eq!(events_4.len(), 1);
6575 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6577 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, .. } } => {
6578 assert!(update_add_htlcs.is_empty());
6579 assert!(update_fulfill_htlcs.is_empty());
6580 assert_eq!(update_fail_htlcs.len(), 1);
6581 assert!(update_fail_malformed_htlcs.is_empty());
6582 assert!(update_fee.is_none());
6584 _ => panic!("Unexpected event"),
6587 check_added_monitors!(nodes[1], 1);
6591 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6592 let chanmon_cfgs = create_chanmon_cfgs(3);
6593 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6594 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6595 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6596 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6597 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6599 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6602 let mut payment_event = {
6603 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6604 check_added_monitors!(nodes[0], 1);
6605 SendEvent::from_node(&nodes[0])
6608 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6609 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6610 expect_pending_htlcs_forwardable!(nodes[1]);
6611 check_added_monitors!(nodes[1], 1);
6612 payment_event = SendEvent::from_node(&nodes[1]);
6613 assert_eq!(payment_event.msgs.len(), 1);
6616 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6617 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6618 check_added_monitors!(nodes[2], 0);
6619 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6621 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6622 assert_eq!(events_3.len(), 1);
6624 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6625 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6626 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6627 update_msg.failure_code |= 0x2000;
6629 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6630 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6632 _ => panic!("Unexpected event"),
6635 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6636 vec![HTLCDestination::NextHopChannel {
6637 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6638 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6639 assert_eq!(events_4.len(), 1);
6640 check_added_monitors!(nodes[1], 1);
6643 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6644 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6645 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6647 _ => panic!("Unexpected event"),
6650 let events_5 = nodes[0].node.get_and_clear_pending_events();
6651 assert_eq!(events_5.len(), 1);
6653 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6654 // the node originating the error to its next hop.
6656 Event::PaymentPathFailed { network_update:
6657 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
6659 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6660 assert!(is_permanent);
6661 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6663 _ => panic!("Unexpected event"),
6666 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6669 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6670 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6671 // 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
6672 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6674 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6675 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6676 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6677 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6678 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6679 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6681 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6683 // We route 2 dust-HTLCs between A and B
6684 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6685 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6686 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6688 // Cache one local commitment tx as previous
6689 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6691 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6692 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6693 check_added_monitors!(nodes[1], 0);
6694 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6695 check_added_monitors!(nodes[1], 1);
6697 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6698 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6699 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6700 check_added_monitors!(nodes[0], 1);
6702 // Cache one local commitment tx as lastest
6703 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6705 let events = nodes[0].node.get_and_clear_pending_msg_events();
6707 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6708 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6710 _ => panic!("Unexpected event"),
6713 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6714 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6716 _ => panic!("Unexpected event"),
6719 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6720 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6721 if announce_latest {
6722 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6724 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6727 check_closed_broadcast!(nodes[0], true);
6728 check_added_monitors!(nodes[0], 1);
6729 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6731 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6732 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6733 let events = nodes[0].node.get_and_clear_pending_events();
6734 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6735 assert_eq!(events.len(), 2);
6736 let mut first_failed = false;
6737 for event in events {
6739 Event::PaymentPathFailed { payment_hash, .. } => {
6740 if payment_hash == payment_hash_1 {
6741 assert!(!first_failed);
6742 first_failed = true;
6744 assert_eq!(payment_hash, payment_hash_2);
6747 _ => panic!("Unexpected event"),
6753 fn test_failure_delay_dust_htlc_local_commitment() {
6754 do_test_failure_delay_dust_htlc_local_commitment(true);
6755 do_test_failure_delay_dust_htlc_local_commitment(false);
6758 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6759 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6760 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6761 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6762 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6763 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6764 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6766 let chanmon_cfgs = create_chanmon_cfgs(3);
6767 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6768 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6769 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6770 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6772 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6774 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6775 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6777 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6778 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6780 // We revoked bs_commitment_tx
6782 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6783 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6786 let mut timeout_tx = Vec::new();
6788 // We fail dust-HTLC 1 by broadcast of local commitment tx
6789 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6790 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6791 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6792 expect_payment_failed!(nodes[0], dust_hash, false);
6794 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6795 check_closed_broadcast!(nodes[0], true);
6796 check_added_monitors!(nodes[0], 1);
6797 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6798 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
6799 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6800 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6801 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6802 mine_transaction(&nodes[0], &timeout_tx[0]);
6803 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6804 expect_payment_failed!(nodes[0], non_dust_hash, false);
6806 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6807 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6808 check_closed_broadcast!(nodes[0], true);
6809 check_added_monitors!(nodes[0], 1);
6810 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6811 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6813 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6814 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6815 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6816 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6817 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6818 // dust HTLC should have been failed.
6819 expect_payment_failed!(nodes[0], dust_hash, false);
6822 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6824 assert_eq!(timeout_tx[0].lock_time.0, 0);
6826 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6827 mine_transaction(&nodes[0], &timeout_tx[0]);
6828 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6829 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6830 expect_payment_failed!(nodes[0], non_dust_hash, false);
6835 fn test_sweep_outbound_htlc_failure_update() {
6836 do_test_sweep_outbound_htlc_failure_update(false, true);
6837 do_test_sweep_outbound_htlc_failure_update(false, false);
6838 do_test_sweep_outbound_htlc_failure_update(true, false);
6842 fn test_user_configurable_csv_delay() {
6843 // We test our channel constructors yield errors when we pass them absurd csv delay
6845 let mut low_our_to_self_config = UserConfig::default();
6846 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6847 let mut high_their_to_self_config = UserConfig::default();
6848 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6849 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6850 let chanmon_cfgs = create_chanmon_cfgs(2);
6851 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6852 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6853 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6855 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6856 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6857 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
6858 &low_our_to_self_config, 0, 42)
6861 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())); },
6862 _ => panic!("Unexpected event"),
6864 } else { assert!(false) }
6866 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6867 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6868 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6869 open_channel.to_self_delay = 200;
6870 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6871 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6872 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6875 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())); },
6876 _ => panic!("Unexpected event"),
6878 } else { assert!(false); }
6880 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6881 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6882 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()));
6883 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6884 accept_channel.to_self_delay = 200;
6885 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
6887 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6889 &ErrorAction::SendErrorMessage { ref msg } => {
6890 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()));
6891 reason_msg = msg.data.clone();
6895 } else { panic!(); }
6896 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6898 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6899 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6900 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6901 open_channel.to_self_delay = 200;
6902 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6903 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6904 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6907 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())); },
6908 _ => panic!("Unexpected event"),
6910 } else { assert!(false); }
6914 fn test_check_htlc_underpaying() {
6915 // Send payment through A -> B but A is maliciously
6916 // sending a probe payment (i.e less than expected value0
6917 // to B, B should refuse payment.
6919 let chanmon_cfgs = create_chanmon_cfgs(2);
6920 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6921 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6922 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6924 // Create some initial channels
6925 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6927 let scorer = test_utils::TestScorer::with_penalty(0);
6928 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6929 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
6930 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();
6931 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6932 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
6933 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6934 check_added_monitors!(nodes[0], 1);
6936 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6937 assert_eq!(events.len(), 1);
6938 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6939 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6940 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6942 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6943 // and then will wait a second random delay before failing the HTLC back:
6944 expect_pending_htlcs_forwardable!(nodes[1]);
6945 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6947 // Node 3 is expecting payment of 100_000 but received 10_000,
6948 // it should fail htlc like we didn't know the preimage.
6949 nodes[1].node.process_pending_htlc_forwards();
6951 let events = nodes[1].node.get_and_clear_pending_msg_events();
6952 assert_eq!(events.len(), 1);
6953 let (update_fail_htlc, commitment_signed) = match events[0] {
6954 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 } } => {
6955 assert!(update_add_htlcs.is_empty());
6956 assert!(update_fulfill_htlcs.is_empty());
6957 assert_eq!(update_fail_htlcs.len(), 1);
6958 assert!(update_fail_malformed_htlcs.is_empty());
6959 assert!(update_fee.is_none());
6960 (update_fail_htlcs[0].clone(), commitment_signed)
6962 _ => panic!("Unexpected event"),
6964 check_added_monitors!(nodes[1], 1);
6966 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6967 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6969 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
6970 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
6971 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
6972 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6976 fn test_announce_disable_channels() {
6977 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
6978 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6980 let chanmon_cfgs = create_chanmon_cfgs(2);
6981 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6982 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6983 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6985 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6986 create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6987 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6990 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6991 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6993 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
6994 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
6995 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6996 assert_eq!(msg_events.len(), 3);
6997 let mut chans_disabled = HashMap::new();
6998 for e in msg_events {
7000 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7001 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7002 // Check that each channel gets updated exactly once
7003 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7004 panic!("Generated ChannelUpdate for wrong chan!");
7007 _ => panic!("Unexpected event"),
7011 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7012 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7013 assert_eq!(reestablish_1.len(), 3);
7014 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7015 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7016 assert_eq!(reestablish_2.len(), 3);
7018 // Reestablish chan_1
7019 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7020 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7021 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7022 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7023 // Reestablish chan_2
7024 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7025 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7026 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7027 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7028 // Reestablish chan_3
7029 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7030 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7031 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7032 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7034 nodes[0].node.timer_tick_occurred();
7035 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7036 nodes[0].node.timer_tick_occurred();
7037 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7038 assert_eq!(msg_events.len(), 3);
7039 for e in msg_events {
7041 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7042 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7043 match chans_disabled.remove(&msg.contents.short_channel_id) {
7044 // Each update should have a higher timestamp than the previous one, replacing
7046 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7047 None => panic!("Generated ChannelUpdate for wrong chan!"),
7050 _ => panic!("Unexpected event"),
7053 // Check that each channel gets updated exactly once
7054 assert!(chans_disabled.is_empty());
7058 fn test_bump_penalty_txn_on_revoked_commitment() {
7059 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7060 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7062 let chanmon_cfgs = create_chanmon_cfgs(2);
7063 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7064 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7065 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7067 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7069 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7070 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7071 .with_features(channelmanager::provided_invoice_features());
7072 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7073 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7075 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7076 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7077 assert_eq!(revoked_txn[0].output.len(), 4);
7078 assert_eq!(revoked_txn[0].input.len(), 1);
7079 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7080 let revoked_txid = revoked_txn[0].txid();
7082 let mut penalty_sum = 0;
7083 for outp in revoked_txn[0].output.iter() {
7084 if outp.script_pubkey.is_v0_p2wsh() {
7085 penalty_sum += outp.value;
7089 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7090 let header_114 = connect_blocks(&nodes[1], 14);
7092 // Actually revoke tx by claiming a HTLC
7093 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7094 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7095 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7096 check_added_monitors!(nodes[1], 1);
7098 // One or more justice tx should have been broadcast, check it
7102 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7103 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7104 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7105 assert_eq!(node_txn[0].output.len(), 1);
7106 check_spends!(node_txn[0], revoked_txn[0]);
7107 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7108 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7109 penalty_1 = node_txn[0].txid();
7113 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7114 connect_blocks(&nodes[1], 15);
7115 let mut penalty_2 = penalty_1;
7116 let mut feerate_2 = 0;
7118 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7119 assert_eq!(node_txn.len(), 1);
7120 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7121 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7122 assert_eq!(node_txn[0].output.len(), 1);
7123 check_spends!(node_txn[0], revoked_txn[0]);
7124 penalty_2 = node_txn[0].txid();
7125 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7126 assert_ne!(penalty_2, penalty_1);
7127 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7128 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7129 // Verify 25% bump heuristic
7130 assert!(feerate_2 * 100 >= feerate_1 * 125);
7134 assert_ne!(feerate_2, 0);
7136 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7137 connect_blocks(&nodes[1], 1);
7139 let mut feerate_3 = 0;
7141 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7142 assert_eq!(node_txn.len(), 1);
7143 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7144 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7145 assert_eq!(node_txn[0].output.len(), 1);
7146 check_spends!(node_txn[0], revoked_txn[0]);
7147 penalty_3 = node_txn[0].txid();
7148 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7149 assert_ne!(penalty_3, penalty_2);
7150 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7151 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7152 // Verify 25% bump heuristic
7153 assert!(feerate_3 * 100 >= feerate_2 * 125);
7157 assert_ne!(feerate_3, 0);
7159 nodes[1].node.get_and_clear_pending_events();
7160 nodes[1].node.get_and_clear_pending_msg_events();
7164 fn test_bump_penalty_txn_on_revoked_htlcs() {
7165 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7166 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7168 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7169 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7170 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7171 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7172 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7174 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7175 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7176 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7177 let scorer = test_utils::TestScorer::with_penalty(0);
7178 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7179 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7180 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7181 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7182 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7183 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7184 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7185 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7187 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7188 assert_eq!(revoked_local_txn[0].input.len(), 1);
7189 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7191 // Revoke local commitment tx
7192 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7194 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7195 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7196 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7197 check_closed_broadcast!(nodes[1], true);
7198 check_added_monitors!(nodes[1], 1);
7199 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7200 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7202 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7203 assert_eq!(revoked_htlc_txn.len(), 3);
7204 check_spends!(revoked_htlc_txn[1], chan.3);
7206 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7207 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7208 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7210 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7211 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7212 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7213 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7215 // Broadcast set of revoked txn on A
7216 let hash_128 = connect_blocks(&nodes[0], 40);
7217 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7218 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7219 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7220 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7221 let events = nodes[0].node.get_and_clear_pending_events();
7222 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7223 match events.last().unwrap() {
7224 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7225 _ => panic!("Unexpected event"),
7231 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7232 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7233 // Verify claim tx are spending revoked HTLC txn
7235 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7236 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7237 // which are included in the same block (they are broadcasted because we scan the
7238 // transactions linearly and generate claims as we go, they likely should be removed in the
7240 assert_eq!(node_txn[0].input.len(), 1);
7241 check_spends!(node_txn[0], revoked_local_txn[0]);
7242 assert_eq!(node_txn[1].input.len(), 1);
7243 check_spends!(node_txn[1], revoked_local_txn[0]);
7244 assert_eq!(node_txn[2].input.len(), 1);
7245 check_spends!(node_txn[2], revoked_local_txn[0]);
7247 // Each of the three justice transactions claim a separate (single) output of the three
7248 // available, which we check here:
7249 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7250 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7251 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7253 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7254 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7256 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7257 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7258 // a remote commitment tx has already been confirmed).
7259 check_spends!(node_txn[3], chan.3);
7261 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7262 // output, checked above).
7263 assert_eq!(node_txn[4].input.len(), 2);
7264 assert_eq!(node_txn[4].output.len(), 1);
7265 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7267 first = node_txn[4].txid();
7268 // Store both feerates for later comparison
7269 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7270 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7271 penalty_txn = vec![node_txn[2].clone()];
7275 // Connect one more block to see if bumped penalty are issued for HTLC txn
7276 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7277 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7278 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7279 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7281 // Few more blocks to confirm penalty txn
7282 connect_blocks(&nodes[0], 4);
7283 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7284 let header_144 = connect_blocks(&nodes[0], 9);
7286 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7287 assert_eq!(node_txn.len(), 1);
7289 assert_eq!(node_txn[0].input.len(), 2);
7290 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7291 // Verify bumped tx is different and 25% bump heuristic
7292 assert_ne!(first, node_txn[0].txid());
7293 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7294 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7295 assert!(feerate_2 * 100 > feerate_1 * 125);
7296 let txn = vec![node_txn[0].clone()];
7300 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7301 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7302 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7303 connect_blocks(&nodes[0], 20);
7305 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7306 // We verify than no new transaction has been broadcast because previously
7307 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7308 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7309 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7310 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7311 // up bumped justice generation.
7312 assert_eq!(node_txn.len(), 0);
7315 check_closed_broadcast!(nodes[0], true);
7316 check_added_monitors!(nodes[0], 1);
7320 fn test_bump_penalty_txn_on_remote_commitment() {
7321 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7322 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7325 // Provide preimage for one
7326 // Check aggregation
7328 let chanmon_cfgs = create_chanmon_cfgs(2);
7329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7331 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7333 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7334 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7335 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7337 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7338 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7339 assert_eq!(remote_txn[0].output.len(), 4);
7340 assert_eq!(remote_txn[0].input.len(), 1);
7341 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7343 // Claim a HTLC without revocation (provide B monitor with preimage)
7344 nodes[1].node.claim_funds(payment_preimage);
7345 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7346 mine_transaction(&nodes[1], &remote_txn[0]);
7347 check_added_monitors!(nodes[1], 2);
7348 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7350 // One or more claim tx should have been broadcast, check it
7354 let feerate_timeout;
7355 let feerate_preimage;
7357 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7358 // 5 transactions including:
7359 // local commitment + HTLC-Success
7360 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7361 assert_eq!(node_txn.len(), 5);
7362 assert_eq!(node_txn[0].input.len(), 1);
7363 assert_eq!(node_txn[3].input.len(), 1);
7364 assert_eq!(node_txn[4].input.len(), 1);
7365 check_spends!(node_txn[0], remote_txn[0]);
7366 check_spends!(node_txn[3], remote_txn[0]);
7367 check_spends!(node_txn[4], remote_txn[0]);
7369 check_spends!(node_txn[1], chan.3); // local commitment
7370 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
7372 preimage = node_txn[0].txid();
7373 let index = node_txn[0].input[0].previous_output.vout;
7374 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7375 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7377 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
7378 (node_txn[3].clone(), node_txn[4].clone())
7380 (node_txn[4].clone(), node_txn[3].clone())
7383 preimage_bump = preimage_bump_tx;
7384 check_spends!(preimage_bump, remote_txn[0]);
7385 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7387 timeout = timeout_tx.txid();
7388 let index = timeout_tx.input[0].previous_output.vout;
7389 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7390 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7394 assert_ne!(feerate_timeout, 0);
7395 assert_ne!(feerate_preimage, 0);
7397 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7398 connect_blocks(&nodes[1], 15);
7400 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7401 assert_eq!(node_txn.len(), 1);
7402 assert_eq!(node_txn[0].input.len(), 1);
7403 assert_eq!(preimage_bump.input.len(), 1);
7404 check_spends!(node_txn[0], remote_txn[0]);
7405 check_spends!(preimage_bump, remote_txn[0]);
7407 let index = preimage_bump.input[0].previous_output.vout;
7408 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7409 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7410 assert!(new_feerate * 100 > feerate_timeout * 125);
7411 assert_ne!(timeout, preimage_bump.txid());
7413 let index = node_txn[0].input[0].previous_output.vout;
7414 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7415 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7416 assert!(new_feerate * 100 > feerate_preimage * 125);
7417 assert_ne!(preimage, node_txn[0].txid());
7422 nodes[1].node.get_and_clear_pending_events();
7423 nodes[1].node.get_and_clear_pending_msg_events();
7427 fn test_counterparty_raa_skip_no_crash() {
7428 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7429 // commitment transaction, we would have happily carried on and provided them the next
7430 // commitment transaction based on one RAA forward. This would probably eventually have led to
7431 // channel closure, but it would not have resulted in funds loss. Still, our
7432 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7433 // check simply that the channel is closed in response to such an RAA, but don't check whether
7434 // we decide to punish our counterparty for revoking their funds (as we don't currently
7436 let chanmon_cfgs = create_chanmon_cfgs(2);
7437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7439 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7440 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
7442 let per_commitment_secret;
7443 let next_per_commitment_point;
7445 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7446 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7448 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7450 // Make signer believe we got a counterparty signature, so that it allows the revocation
7451 keys.get_enforcement_state().last_holder_commitment -= 1;
7452 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7454 // Must revoke without gaps
7455 keys.get_enforcement_state().last_holder_commitment -= 1;
7456 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7458 keys.get_enforcement_state().last_holder_commitment -= 1;
7459 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7460 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7463 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7464 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7465 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7466 check_added_monitors!(nodes[1], 1);
7467 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7471 fn test_bump_txn_sanitize_tracking_maps() {
7472 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7473 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7475 let chanmon_cfgs = create_chanmon_cfgs(2);
7476 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7477 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7478 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7480 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7481 // Lock HTLC in both directions
7482 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7483 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7485 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7486 assert_eq!(revoked_local_txn[0].input.len(), 1);
7487 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7489 // Revoke local commitment tx
7490 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7492 // Broadcast set of revoked txn on A
7493 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7494 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7495 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7497 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7498 check_closed_broadcast!(nodes[0], true);
7499 check_added_monitors!(nodes[0], 1);
7500 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7502 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7503 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7504 check_spends!(node_txn[0], revoked_local_txn[0]);
7505 check_spends!(node_txn[1], revoked_local_txn[0]);
7506 check_spends!(node_txn[2], revoked_local_txn[0]);
7507 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7511 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7512 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7513 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7515 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7516 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7517 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7522 fn test_pending_claimed_htlc_no_balance_underflow() {
7523 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7524 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7525 let chanmon_cfgs = create_chanmon_cfgs(2);
7526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7528 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7529 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7531 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7532 nodes[1].node.claim_funds(payment_preimage);
7533 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7534 check_added_monitors!(nodes[1], 1);
7535 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7537 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7538 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7539 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7540 check_added_monitors!(nodes[0], 1);
7541 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7543 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7544 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7545 // can get our balance.
7547 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7548 // the public key of the only hop. This works around ChannelDetails not showing the
7549 // almost-claimed HTLC as available balance.
7550 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7551 route.payment_params = None; // This is all wrong, but unnecessary
7552 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7553 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7554 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7556 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7560 fn test_channel_conf_timeout() {
7561 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7562 // confirm within 2016 blocks, as recommended by BOLT 2.
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, None]);
7566 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7568 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());
7570 // The outbound node should wait forever for confirmation:
7571 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7572 // copied here instead of directly referencing the constant.
7573 connect_blocks(&nodes[0], 2016);
7574 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7576 // The inbound node should fail the channel after exactly 2016 blocks
7577 connect_blocks(&nodes[1], 2015);
7578 check_added_monitors!(nodes[1], 0);
7579 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7581 connect_blocks(&nodes[1], 1);
7582 check_added_monitors!(nodes[1], 1);
7583 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7584 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7585 assert_eq!(close_ev.len(), 1);
7587 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7588 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7589 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7591 _ => panic!("Unexpected event"),
7596 fn test_override_channel_config() {
7597 let chanmon_cfgs = create_chanmon_cfgs(2);
7598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7600 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7602 // Node0 initiates a channel to node1 using the override config.
7603 let mut override_config = UserConfig::default();
7604 override_config.channel_handshake_config.our_to_self_delay = 200;
7606 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7608 // Assert the channel created by node0 is using the override config.
7609 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7610 assert_eq!(res.channel_flags, 0);
7611 assert_eq!(res.to_self_delay, 200);
7615 fn test_override_0msat_htlc_minimum() {
7616 let mut zero_config = UserConfig::default();
7617 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7618 let chanmon_cfgs = create_chanmon_cfgs(2);
7619 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7620 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7621 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7623 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7624 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7625 assert_eq!(res.htlc_minimum_msat, 1);
7627 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7628 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7629 assert_eq!(res.htlc_minimum_msat, 1);
7633 fn test_channel_update_has_correct_htlc_maximum_msat() {
7634 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7635 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7636 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7637 // 90% of the `channel_value`.
7638 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7640 let mut config_30_percent = UserConfig::default();
7641 config_30_percent.channel_handshake_config.announced_channel = true;
7642 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7643 let mut config_50_percent = UserConfig::default();
7644 config_50_percent.channel_handshake_config.announced_channel = true;
7645 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7646 let mut config_95_percent = UserConfig::default();
7647 config_95_percent.channel_handshake_config.announced_channel = true;
7648 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7649 let mut config_100_percent = UserConfig::default();
7650 config_100_percent.channel_handshake_config.announced_channel = true;
7651 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7653 let chanmon_cfgs = create_chanmon_cfgs(4);
7654 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7655 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)]);
7656 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7658 let channel_value_satoshis = 100000;
7659 let channel_value_msat = channel_value_satoshis * 1000;
7660 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7661 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7662 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7664 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());
7665 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());
7667 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7668 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7669 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7670 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7671 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7672 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7674 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7675 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7677 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7678 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7679 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7681 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7685 fn test_manually_accept_inbound_channel_request() {
7686 let mut manually_accept_conf = UserConfig::default();
7687 manually_accept_conf.manually_accept_inbound_channels = true;
7688 let chanmon_cfgs = create_chanmon_cfgs(2);
7689 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7690 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7691 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7693 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7694 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7696 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7698 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7699 // accepting the inbound channel request.
7700 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7702 let events = nodes[1].node.get_and_clear_pending_events();
7704 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7705 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7707 _ => panic!("Unexpected event"),
7710 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7711 assert_eq!(accept_msg_ev.len(), 1);
7713 match accept_msg_ev[0] {
7714 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7715 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7717 _ => panic!("Unexpected event"),
7720 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7722 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7723 assert_eq!(close_msg_ev.len(), 1);
7725 let events = nodes[1].node.get_and_clear_pending_events();
7727 Event::ChannelClosed { user_channel_id, .. } => {
7728 assert_eq!(user_channel_id, 23);
7730 _ => panic!("Unexpected event"),
7735 fn test_manually_reject_inbound_channel_request() {
7736 let mut manually_accept_conf = UserConfig::default();
7737 manually_accept_conf.manually_accept_inbound_channels = true;
7738 let chanmon_cfgs = create_chanmon_cfgs(2);
7739 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7740 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7741 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7743 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7744 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7746 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7748 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7749 // rejecting the inbound channel request.
7750 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7752 let events = nodes[1].node.get_and_clear_pending_events();
7754 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7755 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7757 _ => panic!("Unexpected event"),
7760 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7761 assert_eq!(close_msg_ev.len(), 1);
7763 match close_msg_ev[0] {
7764 MessageSendEvent::HandleError { ref node_id, .. } => {
7765 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7767 _ => panic!("Unexpected event"),
7769 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7773 fn test_reject_funding_before_inbound_channel_accepted() {
7774 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7775 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7776 // the node operator before the counterparty sends a `FundingCreated` message. If a
7777 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7778 // and the channel should be closed.
7779 let mut manually_accept_conf = UserConfig::default();
7780 manually_accept_conf.manually_accept_inbound_channels = true;
7781 let chanmon_cfgs = create_chanmon_cfgs(2);
7782 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7783 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7784 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7786 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7787 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7788 let temp_channel_id = res.temporary_channel_id;
7790 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7792 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7793 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7795 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7796 nodes[1].node.get_and_clear_pending_events();
7798 // Get the `AcceptChannel` message of `nodes[1]` without calling
7799 // `ChannelManager::accept_inbound_channel`, which generates a
7800 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7801 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7802 // succeed when `nodes[0]` is passed to it.
7803 let accept_chan_msg = {
7805 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
7806 channel.get_accept_channel_message()
7808 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
7810 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7812 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7813 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7815 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7816 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7818 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7819 assert_eq!(close_msg_ev.len(), 1);
7821 let expected_err = "FundingCreated message received before the channel was accepted";
7822 match close_msg_ev[0] {
7823 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7824 assert_eq!(msg.channel_id, temp_channel_id);
7825 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7826 assert_eq!(msg.data, expected_err);
7828 _ => panic!("Unexpected event"),
7831 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7835 fn test_can_not_accept_inbound_channel_twice() {
7836 let mut manually_accept_conf = UserConfig::default();
7837 manually_accept_conf.manually_accept_inbound_channels = true;
7838 let chanmon_cfgs = create_chanmon_cfgs(2);
7839 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7840 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7841 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7843 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7844 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7846 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7848 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7849 // accepting the inbound channel request.
7850 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7852 let events = nodes[1].node.get_and_clear_pending_events();
7854 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7855 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7856 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7858 Err(APIError::APIMisuseError { err }) => {
7859 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7861 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7862 Err(_) => panic!("Unexpected Error"),
7865 _ => panic!("Unexpected event"),
7868 // Ensure that the channel wasn't closed after attempting to accept it twice.
7869 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7870 assert_eq!(accept_msg_ev.len(), 1);
7872 match accept_msg_ev[0] {
7873 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7874 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7876 _ => panic!("Unexpected event"),
7881 fn test_can_not_accept_unknown_inbound_channel() {
7882 let chanmon_cfg = create_chanmon_cfgs(2);
7883 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7884 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7885 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7887 let unknown_channel_id = [0; 32];
7888 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7890 Err(APIError::ChannelUnavailable { err }) => {
7891 assert_eq!(err, "Can't accept a channel that doesn't exist");
7893 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7894 Err(_) => panic!("Unexpected Error"),
7899 fn test_simple_mpp() {
7900 // Simple test of sending a multi-path payment.
7901 let chanmon_cfgs = create_chanmon_cfgs(4);
7902 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7903 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7904 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7906 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;
7907 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;
7908 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;
7909 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;
7911 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7912 let path = route.paths[0].clone();
7913 route.paths.push(path);
7914 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7915 route.paths[0][0].short_channel_id = chan_1_id;
7916 route.paths[0][1].short_channel_id = chan_3_id;
7917 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7918 route.paths[1][0].short_channel_id = chan_2_id;
7919 route.paths[1][1].short_channel_id = chan_4_id;
7920 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7921 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7925 fn test_preimage_storage() {
7926 // Simple test of payment preimage storage allowing no client-side storage to claim payments
7927 let chanmon_cfgs = create_chanmon_cfgs(2);
7928 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7929 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7930 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7932 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7935 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
7936 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7937 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7938 check_added_monitors!(nodes[0], 1);
7939 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7940 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7942 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7944 // Note that after leaving the above scope we have no knowledge of any arguments or return
7945 // values from previous calls.
7946 expect_pending_htlcs_forwardable!(nodes[1]);
7947 let events = nodes[1].node.get_and_clear_pending_events();
7948 assert_eq!(events.len(), 1);
7950 Event::PaymentReceived { ref purpose, .. } => {
7952 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7953 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7955 _ => panic!("expected PaymentPurpose::InvoicePayment")
7958 _ => panic!("Unexpected event"),
7963 #[allow(deprecated)]
7964 fn test_secret_timeout() {
7965 // Simple test of payment secret storage time outs. After
7966 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7967 let chanmon_cfgs = create_chanmon_cfgs(2);
7968 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7969 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7970 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7972 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7974 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
7976 // We should fail to register the same payment hash twice, at least until we've connected a
7977 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
7978 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7979 assert_eq!(err, "Duplicate payment hash");
7980 } else { panic!(); }
7982 let node_1_blocks = nodes[1].blocks.lock().unwrap();
7984 header: BlockHeader {
7986 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
7987 merkle_root: TxMerkleNode::all_zeros(),
7988 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
7992 connect_block(&nodes[1], &block);
7993 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7994 assert_eq!(err, "Duplicate payment hash");
7995 } else { panic!(); }
7997 // If we then connect the second block, we should be able to register the same payment hash
7998 // again (this time getting a new payment secret).
7999 block.header.prev_blockhash = block.header.block_hash();
8000 block.header.time += 1;
8001 connect_block(&nodes[1], &block);
8002 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8003 assert_ne!(payment_secret_1, our_payment_secret);
8006 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8007 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8008 check_added_monitors!(nodes[0], 1);
8009 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8010 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8011 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8012 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8014 // Note that after leaving the above scope we have no knowledge of any arguments or return
8015 // values from previous calls.
8016 expect_pending_htlcs_forwardable!(nodes[1]);
8017 let events = nodes[1].node.get_and_clear_pending_events();
8018 assert_eq!(events.len(), 1);
8020 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8021 assert!(payment_preimage.is_none());
8022 assert_eq!(payment_secret, our_payment_secret);
8023 // We don't actually have the payment preimage with which to claim this payment!
8025 _ => panic!("Unexpected event"),
8030 fn test_bad_secret_hash() {
8031 // Simple test of unregistered payment hash/invalid payment secret handling
8032 let chanmon_cfgs = create_chanmon_cfgs(2);
8033 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8034 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8035 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8037 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8039 let random_payment_hash = PaymentHash([42; 32]);
8040 let random_payment_secret = PaymentSecret([43; 32]);
8041 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8042 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8044 // All the below cases should end up being handled exactly identically, so we macro the
8045 // resulting events.
8046 macro_rules! handle_unknown_invalid_payment_data {
8047 ($payment_hash: expr) => {
8048 check_added_monitors!(nodes[0], 1);
8049 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8050 let payment_event = SendEvent::from_event(events.pop().unwrap());
8051 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8052 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8054 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8055 // again to process the pending backwards-failure of the HTLC
8056 expect_pending_htlcs_forwardable!(nodes[1]);
8057 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8058 check_added_monitors!(nodes[1], 1);
8060 // We should fail the payment back
8061 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8062 match events.pop().unwrap() {
8063 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8064 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8065 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8067 _ => panic!("Unexpected event"),
8072 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8073 // Error data is the HTLC value (100,000) and current block height
8074 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8076 // Send a payment with the right payment hash but the wrong payment secret
8077 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8078 handle_unknown_invalid_payment_data!(our_payment_hash);
8079 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8081 // Send a payment with a random payment hash, but the right payment secret
8082 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8083 handle_unknown_invalid_payment_data!(random_payment_hash);
8084 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8086 // Send a payment with a random payment hash and random payment secret
8087 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8088 handle_unknown_invalid_payment_data!(random_payment_hash);
8089 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8093 fn test_update_err_monitor_lockdown() {
8094 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8095 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8096 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8099 // This scenario may happen in a watchtower setup, where watchtower process a block height
8100 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8101 // commitment at same time.
8103 let chanmon_cfgs = create_chanmon_cfgs(2);
8104 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8105 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8106 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8108 // Create some initial channel
8109 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8110 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8112 // Rebalance the network to generate htlc in the two directions
8113 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8115 // Route a HTLC from node 0 to node 1 (but don't settle)
8116 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8118 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8119 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8120 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8121 let persister = test_utils::TestPersister::new();
8123 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8124 let mut w = test_utils::TestVecWriter(Vec::new());
8125 monitor.write(&mut w).unwrap();
8126 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8127 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8128 assert!(new_monitor == *monitor);
8129 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);
8130 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8133 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8134 let block = Block { header, txdata: vec![] };
8135 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8136 // transaction lock time requirements here.
8137 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8138 watchtower.chain_monitor.block_connected(&block, 200);
8140 // Try to update ChannelMonitor
8141 nodes[1].node.claim_funds(preimage);
8142 check_added_monitors!(nodes[1], 1);
8143 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8145 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8146 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8147 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8148 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8149 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8150 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8151 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8152 } else { assert!(false); }
8153 } else { assert!(false); };
8154 // Our local monitor is in-sync and hasn't processed yet timeout
8155 check_added_monitors!(nodes[0], 1);
8156 let events = nodes[0].node.get_and_clear_pending_events();
8157 assert_eq!(events.len(), 1);
8161 fn test_concurrent_monitor_claim() {
8162 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8163 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8164 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8165 // state N+1 confirms. Alice claims output from state N+1.
8167 let chanmon_cfgs = create_chanmon_cfgs(2);
8168 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8169 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8170 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8172 // Create some initial channel
8173 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8174 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8176 // Rebalance the network to generate htlc in the two directions
8177 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8179 // Route a HTLC from node 0 to node 1 (but don't settle)
8180 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8182 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8183 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8184 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8185 let persister = test_utils::TestPersister::new();
8186 let watchtower_alice = {
8187 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8188 let mut w = test_utils::TestVecWriter(Vec::new());
8189 monitor.write(&mut w).unwrap();
8190 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8191 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8192 assert!(new_monitor == *monitor);
8193 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);
8194 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8197 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8198 let block = Block { header, txdata: vec![] };
8199 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8200 // transaction lock time requirements here.
8201 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));
8202 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8204 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8206 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8207 assert_eq!(txn.len(), 2);
8211 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8212 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8213 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8214 let persister = test_utils::TestPersister::new();
8215 let watchtower_bob = {
8216 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8217 let mut w = test_utils::TestVecWriter(Vec::new());
8218 monitor.write(&mut w).unwrap();
8219 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8220 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8221 assert!(new_monitor == *monitor);
8222 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);
8223 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8226 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8227 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8229 // Route another payment to generate another update with still previous HTLC pending
8230 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8232 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8234 check_added_monitors!(nodes[1], 1);
8236 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8237 assert_eq!(updates.update_add_htlcs.len(), 1);
8238 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8239 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8240 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8241 // Watchtower Alice should already have seen the block and reject the update
8242 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8243 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8244 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8245 } else { assert!(false); }
8246 } else { assert!(false); };
8247 // Our local monitor is in-sync and hasn't processed yet timeout
8248 check_added_monitors!(nodes[0], 1);
8250 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8251 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8252 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8254 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8257 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8258 assert_eq!(txn.len(), 2);
8259 bob_state_y = txn[0].clone();
8263 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8264 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8265 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);
8267 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8268 assert_eq!(htlc_txn.len(), 1);
8269 check_spends!(htlc_txn[0], bob_state_y);
8274 fn test_pre_lockin_no_chan_closed_update() {
8275 // Test that if a peer closes a channel in response to a funding_created message we don't
8276 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8279 // Doing so would imply a channel monitor update before the initial channel monitor
8280 // registration, violating our API guarantees.
8282 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8283 // then opening a second channel with the same funding output as the first (which is not
8284 // rejected because the first channel does not exist in the ChannelManager) and closing it
8285 // before receiving funding_signed.
8286 let chanmon_cfgs = create_chanmon_cfgs(2);
8287 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8288 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8289 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8291 // Create an initial channel
8292 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8293 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8294 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8295 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8296 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8298 // Move the first channel through the funding flow...
8299 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8301 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8302 check_added_monitors!(nodes[0], 0);
8304 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8305 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8306 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8307 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8308 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8312 fn test_htlc_no_detection() {
8313 // This test is a mutation to underscore the detection logic bug we had
8314 // before #653. HTLC value routed is above the remaining balance, thus
8315 // inverting HTLC and `to_remote` output. HTLC will come second and
8316 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8317 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8318 // outputs order detection for correct spending children filtring.
8320 let chanmon_cfgs = create_chanmon_cfgs(2);
8321 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8322 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8323 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8325 // Create some initial channels
8326 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8328 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8329 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8330 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8331 assert_eq!(local_txn[0].input.len(), 1);
8332 assert_eq!(local_txn[0].output.len(), 3);
8333 check_spends!(local_txn[0], chan_1.3);
8335 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8336 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8337 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8338 // We deliberately connect the local tx twice as this should provoke a failure calling
8339 // this test before #653 fix.
8340 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);
8341 check_closed_broadcast!(nodes[0], true);
8342 check_added_monitors!(nodes[0], 1);
8343 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8344 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8346 let htlc_timeout = {
8347 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8348 assert_eq!(node_txn[1].input.len(), 1);
8349 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8350 check_spends!(node_txn[1], local_txn[0]);
8354 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8355 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8356 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8357 expect_payment_failed!(nodes[0], our_payment_hash, false);
8360 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8361 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8362 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8363 // Carol, Alice would be the upstream node, and Carol the downstream.)
8365 // Steps of the test:
8366 // 1) Alice sends a HTLC to Carol through Bob.
8367 // 2) Carol doesn't settle the HTLC.
8368 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8369 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8370 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8371 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8372 // 5) Carol release the preimage to Bob off-chain.
8373 // 6) Bob claims the offered output on the broadcasted commitment.
8374 let chanmon_cfgs = create_chanmon_cfgs(3);
8375 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8376 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8377 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8379 // Create some initial channels
8380 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8381 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8383 // Steps (1) and (2):
8384 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8385 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8387 // Check that Alice's commitment transaction now contains an output for this HTLC.
8388 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8389 check_spends!(alice_txn[0], chan_ab.3);
8390 assert_eq!(alice_txn[0].output.len(), 2);
8391 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8392 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8393 assert_eq!(alice_txn.len(), 2);
8395 // Steps (3) and (4):
8396 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8397 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8398 let mut force_closing_node = 0; // Alice force-closes
8399 let mut counterparty_node = 1; // Bob if Alice force-closes
8402 if !broadcast_alice {
8403 force_closing_node = 1;
8404 counterparty_node = 0;
8406 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8407 check_closed_broadcast!(nodes[force_closing_node], true);
8408 check_added_monitors!(nodes[force_closing_node], 1);
8409 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8410 if go_onchain_before_fulfill {
8411 let txn_to_broadcast = match broadcast_alice {
8412 true => alice_txn.clone(),
8413 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8415 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8416 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8417 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8418 if broadcast_alice {
8419 check_closed_broadcast!(nodes[1], true);
8420 check_added_monitors!(nodes[1], 1);
8421 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8423 assert_eq!(bob_txn.len(), 1);
8424 check_spends!(bob_txn[0], chan_ab.3);
8428 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8429 // process of removing the HTLC from their commitment transactions.
8430 nodes[2].node.claim_funds(payment_preimage);
8431 check_added_monitors!(nodes[2], 1);
8432 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8434 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8435 assert!(carol_updates.update_add_htlcs.is_empty());
8436 assert!(carol_updates.update_fail_htlcs.is_empty());
8437 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8438 assert!(carol_updates.update_fee.is_none());
8439 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8441 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8442 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8443 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8444 if !go_onchain_before_fulfill && broadcast_alice {
8445 let events = nodes[1].node.get_and_clear_pending_msg_events();
8446 assert_eq!(events.len(), 1);
8448 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8449 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8451 _ => panic!("Unexpected event"),
8454 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8455 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8456 // Carol<->Bob's updated commitment transaction info.
8457 check_added_monitors!(nodes[1], 2);
8459 let events = nodes[1].node.get_and_clear_pending_msg_events();
8460 assert_eq!(events.len(), 2);
8461 let bob_revocation = match events[0] {
8462 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8463 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8466 _ => panic!("Unexpected event"),
8468 let bob_updates = match events[1] {
8469 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8470 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8473 _ => panic!("Unexpected event"),
8476 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8477 check_added_monitors!(nodes[2], 1);
8478 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8479 check_added_monitors!(nodes[2], 1);
8481 let events = nodes[2].node.get_and_clear_pending_msg_events();
8482 assert_eq!(events.len(), 1);
8483 let carol_revocation = match events[0] {
8484 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8485 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8488 _ => panic!("Unexpected event"),
8490 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8491 check_added_monitors!(nodes[1], 1);
8493 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8494 // here's where we put said channel's commitment tx on-chain.
8495 let mut txn_to_broadcast = alice_txn.clone();
8496 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8497 if !go_onchain_before_fulfill {
8498 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8499 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8500 // If Bob was the one to force-close, he will have already passed these checks earlier.
8501 if broadcast_alice {
8502 check_closed_broadcast!(nodes[1], true);
8503 check_added_monitors!(nodes[1], 1);
8504 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8506 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8507 if broadcast_alice {
8508 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8509 // new block being connected. The ChannelManager being notified triggers a monitor update,
8510 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8511 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8513 assert_eq!(bob_txn.len(), 3);
8514 check_spends!(bob_txn[1], chan_ab.3);
8516 assert_eq!(bob_txn.len(), 2);
8517 check_spends!(bob_txn[0], chan_ab.3);
8522 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8523 // broadcasted commitment transaction.
8525 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8526 if go_onchain_before_fulfill {
8527 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8528 assert_eq!(bob_txn.len(), 2);
8530 let script_weight = match broadcast_alice {
8531 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8532 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8534 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8535 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8536 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8537 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8538 if broadcast_alice && !go_onchain_before_fulfill {
8539 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8540 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8542 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8543 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8549 fn test_onchain_htlc_settlement_after_close() {
8550 do_test_onchain_htlc_settlement_after_close(true, true);
8551 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8552 do_test_onchain_htlc_settlement_after_close(true, false);
8553 do_test_onchain_htlc_settlement_after_close(false, false);
8557 fn test_duplicate_chan_id() {
8558 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8559 // already open we reject it and keep the old channel.
8561 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8562 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8563 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8564 // updating logic for the existing channel.
8565 let chanmon_cfgs = create_chanmon_cfgs(2);
8566 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8567 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8568 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8570 // Create an initial channel
8571 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8572 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8573 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8574 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 // Try to create a second channel with the same temporary_channel_id as the first and check
8577 // that it is rejected.
8578 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8580 let events = nodes[1].node.get_and_clear_pending_msg_events();
8581 assert_eq!(events.len(), 1);
8583 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8584 // Technically, at this point, nodes[1] would be justified in thinking both the
8585 // first (valid) and second (invalid) channels are closed, given they both have
8586 // the same non-temporary channel_id. However, currently we do not, so we just
8587 // move forward with it.
8588 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8589 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8591 _ => panic!("Unexpected event"),
8595 // Move the first channel through the funding flow...
8596 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8598 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8599 check_added_monitors!(nodes[0], 0);
8601 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8602 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8604 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8605 assert_eq!(added_monitors.len(), 1);
8606 assert_eq!(added_monitors[0].0, funding_output);
8607 added_monitors.clear();
8609 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8611 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8612 let channel_id = funding_outpoint.to_channel_id();
8614 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8617 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8618 // Technically this is allowed by the spec, but we don't support it and there's little reason
8619 // to. Still, it shouldn't cause any other issues.
8620 open_chan_msg.temporary_channel_id = channel_id;
8621 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8623 let events = nodes[1].node.get_and_clear_pending_msg_events();
8624 assert_eq!(events.len(), 1);
8626 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8627 // Technically, at this point, nodes[1] would be justified in thinking both
8628 // channels are closed, but currently we do not, so we just move forward with it.
8629 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8630 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8632 _ => panic!("Unexpected event"),
8636 // Now try to create a second channel which has a duplicate funding output.
8637 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8638 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8639 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
8640 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()));
8641 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8643 let funding_created = {
8644 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8645 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8646 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8647 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8648 // channelmanager in a possibly nonsense state instead).
8649 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8650 let logger = test_utils::TestLogger::new();
8651 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8653 check_added_monitors!(nodes[0], 0);
8654 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8655 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8656 // still needs to be cleared here.
8657 check_added_monitors!(nodes[1], 1);
8659 // ...still, nodes[1] will reject the duplicate channel.
8661 let events = nodes[1].node.get_and_clear_pending_msg_events();
8662 assert_eq!(events.len(), 1);
8664 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8665 // Technically, at this point, nodes[1] would be justified in thinking both
8666 // channels are closed, but currently we do not, so we just move forward with it.
8667 assert_eq!(msg.channel_id, channel_id);
8668 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8670 _ => panic!("Unexpected event"),
8674 // finally, finish creating the original channel and send a payment over it to make sure
8675 // everything is functional.
8676 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8678 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8679 assert_eq!(added_monitors.len(), 1);
8680 assert_eq!(added_monitors[0].0, funding_output);
8681 added_monitors.clear();
8684 let events_4 = nodes[0].node.get_and_clear_pending_events();
8685 assert_eq!(events_4.len(), 0);
8686 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8687 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8689 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8690 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8691 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8693 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8697 fn test_error_chans_closed() {
8698 // Test that we properly handle error messages, closing appropriate channels.
8700 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8701 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8702 // we can test various edge cases around it to ensure we don't regress.
8703 let chanmon_cfgs = create_chanmon_cfgs(3);
8704 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8705 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8706 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8708 // Create some initial channels
8709 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8710 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8711 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8713 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8714 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8715 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8717 // Closing a channel from a different peer has no effect
8718 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8719 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8721 // Closing one channel doesn't impact others
8722 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8723 check_added_monitors!(nodes[0], 1);
8724 check_closed_broadcast!(nodes[0], false);
8725 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8726 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8727 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8728 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);
8729 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);
8731 // A null channel ID should close all channels
8732 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8733 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8734 check_added_monitors!(nodes[0], 2);
8735 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8736 let events = nodes[0].node.get_and_clear_pending_msg_events();
8737 assert_eq!(events.len(), 2);
8739 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8740 assert_eq!(msg.contents.flags & 2, 2);
8742 _ => panic!("Unexpected event"),
8745 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8746 assert_eq!(msg.contents.flags & 2, 2);
8748 _ => panic!("Unexpected event"),
8750 // Note that at this point users of a standard PeerHandler will end up calling
8751 // peer_disconnected with no_connection_possible set to false, duplicating the
8752 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8753 // users with their own peer handling logic. We duplicate the call here, however.
8754 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8755 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8757 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8758 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8759 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8763 fn test_invalid_funding_tx() {
8764 // Test that we properly handle invalid funding transactions sent to us from a peer.
8766 // Previously, all other major lightning implementations had failed to properly sanitize
8767 // funding transactions from their counterparties, leading to a multi-implementation critical
8768 // security vulnerability (though we always sanitized properly, we've previously had
8769 // un-released crashes in the sanitization process).
8771 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8772 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8773 // gave up on it. We test this here by generating such a transaction.
8774 let chanmon_cfgs = create_chanmon_cfgs(2);
8775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8777 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8779 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8780 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()));
8781 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()));
8783 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8785 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8786 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8787 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8789 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8790 let wit_program_script: Script = wit_program.into();
8791 for output in tx.output.iter_mut() {
8792 // Make the confirmed funding transaction have a bogus script_pubkey
8793 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8796 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8797 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()));
8798 check_added_monitors!(nodes[1], 1);
8800 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()));
8801 check_added_monitors!(nodes[0], 1);
8803 let events_1 = nodes[0].node.get_and_clear_pending_events();
8804 assert_eq!(events_1.len(), 0);
8806 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8807 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8808 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8810 let expected_err = "funding tx had wrong script/value or output index";
8811 confirm_transaction_at(&nodes[1], &tx, 1);
8812 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8813 check_added_monitors!(nodes[1], 1);
8814 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8815 assert_eq!(events_2.len(), 1);
8816 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8817 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8818 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8819 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8820 } else { panic!(); }
8821 } else { panic!(); }
8822 assert_eq!(nodes[1].node.list_channels().len(), 0);
8824 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8825 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8826 // as its not 32 bytes long.
8827 let mut spend_tx = Transaction {
8828 version: 2i32, lock_time: PackedLockTime::ZERO,
8829 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8830 previous_output: BitcoinOutPoint {
8834 script_sig: Script::new(),
8835 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8836 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8838 output: vec![TxOut {
8840 script_pubkey: Script::new(),
8843 check_spends!(spend_tx, tx);
8844 mine_transaction(&nodes[1], &spend_tx);
8847 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8848 // In the first version of the chain::Confirm interface, after a refactor was made to not
8849 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8850 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8851 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8852 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8853 // spending transaction until height N+1 (or greater). This was due to the way
8854 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8855 // spending transaction at the height the input transaction was confirmed at, not whether we
8856 // should broadcast a spending transaction at the current height.
8857 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8858 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8859 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8860 // until we learned about an additional block.
8862 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8863 // aren't broadcasting transactions too early (ie not broadcasting them at all).
8864 let chanmon_cfgs = create_chanmon_cfgs(3);
8865 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8866 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8867 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8868 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8870 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8871 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8872 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8873 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8874 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8876 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8877 check_closed_broadcast!(nodes[1], true);
8878 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8879 check_added_monitors!(nodes[1], 1);
8880 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8881 assert_eq!(node_txn.len(), 1);
8883 let conf_height = nodes[1].best_block_info().1;
8884 if !test_height_before_timelock {
8885 connect_blocks(&nodes[1], 24 * 6);
8887 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8888 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8889 if test_height_before_timelock {
8890 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8891 // generate any events or broadcast any transactions
8892 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8893 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8895 // We should broadcast an HTLC transaction spending our funding transaction first
8896 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8897 assert_eq!(spending_txn.len(), 2);
8898 assert_eq!(spending_txn[0], node_txn[0]);
8899 check_spends!(spending_txn[1], node_txn[0]);
8900 // We should also generate a SpendableOutputs event with the to_self output (as its
8902 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8903 assert_eq!(descriptor_spend_txn.len(), 1);
8905 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8906 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8907 // additional block built on top of the current chain.
8908 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8909 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8910 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 }]);
8911 check_added_monitors!(nodes[1], 1);
8913 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8914 assert!(updates.update_add_htlcs.is_empty());
8915 assert!(updates.update_fulfill_htlcs.is_empty());
8916 assert_eq!(updates.update_fail_htlcs.len(), 1);
8917 assert!(updates.update_fail_malformed_htlcs.is_empty());
8918 assert!(updates.update_fee.is_none());
8919 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8920 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8921 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
8926 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
8927 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
8928 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
8931 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
8932 let chanmon_cfgs = create_chanmon_cfgs(2);
8933 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8934 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8935 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8937 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8939 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
8940 .with_features(channelmanager::provided_invoice_features());
8941 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
8943 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
8946 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8947 check_added_monitors!(nodes[0], 1);
8948 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8949 assert_eq!(events.len(), 1);
8950 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8951 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8952 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8954 expect_pending_htlcs_forwardable!(nodes[1]);
8955 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
8958 // Note that we use a different PaymentId here to allow us to duplicativly pay
8959 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
8960 check_added_monitors!(nodes[0], 1);
8961 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8962 assert_eq!(events.len(), 1);
8963 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8964 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8965 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8966 // At this point, nodes[1] would notice it has too much value for the payment. It will
8967 // assume the second is a privacy attack (no longer particularly relevant
8968 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
8969 // the first HTLC delivered above.
8972 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
8973 nodes[1].node.process_pending_htlc_forwards();
8975 if test_for_second_fail_panic {
8976 // Now we go fail back the first HTLC from the user end.
8977 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
8979 let expected_destinations = vec![
8980 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8981 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8983 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
8984 nodes[1].node.process_pending_htlc_forwards();
8986 check_added_monitors!(nodes[1], 1);
8987 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8988 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
8990 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
8991 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
8992 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
8994 let failure_events = nodes[0].node.get_and_clear_pending_events();
8995 assert_eq!(failure_events.len(), 2);
8996 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
8997 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
8999 // Let the second HTLC fail and claim the first
9000 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9001 nodes[1].node.process_pending_htlc_forwards();
9003 check_added_monitors!(nodes[1], 1);
9004 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9005 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9006 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9008 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9010 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9015 fn test_dup_htlc_second_fail_panic() {
9016 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9017 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9018 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9019 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9020 do_test_dup_htlc_second_rejected(true);
9024 fn test_dup_htlc_second_rejected() {
9025 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9026 // simply reject the second HTLC but are still able to claim the first HTLC.
9027 do_test_dup_htlc_second_rejected(false);
9031 fn test_inconsistent_mpp_params() {
9032 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9033 // such HTLC and allow the second to stay.
9034 let chanmon_cfgs = create_chanmon_cfgs(4);
9035 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9036 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9037 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9039 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9040 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9041 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9042 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());
9044 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9045 .with_features(channelmanager::provided_invoice_features());
9046 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9047 assert_eq!(route.paths.len(), 2);
9048 route.paths.sort_by(|path_a, _| {
9049 // Sort the path so that the path through nodes[1] comes first
9050 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9051 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9053 let payment_params_opt = Some(payment_params);
9055 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9057 let cur_height = nodes[0].best_block_info().1;
9058 let payment_id = PaymentId([42; 32]);
9060 let session_privs = {
9061 // We create a fake route here so that we start with three pending HTLCs, which we'll
9062 // ultimately have, just not right away.
9063 let mut dup_route = route.clone();
9064 dup_route.paths.push(route.paths[1].clone());
9065 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9068 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();
9069 check_added_monitors!(nodes[0], 1);
9071 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9072 assert_eq!(events.len(), 1);
9073 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9075 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9078 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();
9079 check_added_monitors!(nodes[0], 1);
9081 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9082 assert_eq!(events.len(), 1);
9083 let payment_event = SendEvent::from_event(events.pop().unwrap());
9085 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9086 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9088 expect_pending_htlcs_forwardable!(nodes[2]);
9089 check_added_monitors!(nodes[2], 1);
9091 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9092 assert_eq!(events.len(), 1);
9093 let payment_event = SendEvent::from_event(events.pop().unwrap());
9095 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9096 check_added_monitors!(nodes[3], 0);
9097 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9099 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9100 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9101 // post-payment_secrets) and fail back the new HTLC.
9103 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9104 nodes[3].node.process_pending_htlc_forwards();
9105 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9106 nodes[3].node.process_pending_htlc_forwards();
9108 check_added_monitors!(nodes[3], 1);
9110 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9111 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9112 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9114 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 }]);
9115 check_added_monitors!(nodes[2], 1);
9117 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9118 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9119 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9121 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9123 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();
9124 check_added_monitors!(nodes[0], 1);
9126 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9127 assert_eq!(events.len(), 1);
9128 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9130 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9134 fn test_keysend_payments_to_public_node() {
9135 let chanmon_cfgs = create_chanmon_cfgs(2);
9136 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9137 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9138 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9140 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9141 let network_graph = nodes[0].network_graph;
9142 let payer_pubkey = nodes[0].node.get_our_node_id();
9143 let payee_pubkey = nodes[1].node.get_our_node_id();
9144 let route_params = RouteParameters {
9145 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9146 final_value_msat: 10000,
9147 final_cltv_expiry_delta: 40,
9149 let scorer = test_utils::TestScorer::with_penalty(0);
9150 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9151 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9153 let test_preimage = PaymentPreimage([42; 32]);
9154 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9155 check_added_monitors!(nodes[0], 1);
9156 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9157 assert_eq!(events.len(), 1);
9158 let event = events.pop().unwrap();
9159 let path = vec![&nodes[1]];
9160 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9161 claim_payment(&nodes[0], &path, test_preimage);
9165 fn test_keysend_payments_to_private_node() {
9166 let chanmon_cfgs = create_chanmon_cfgs(2);
9167 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9168 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9169 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9171 let payer_pubkey = nodes[0].node.get_our_node_id();
9172 let payee_pubkey = nodes[1].node.get_our_node_id();
9173 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9174 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9176 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9177 let route_params = RouteParameters {
9178 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9179 final_value_msat: 10000,
9180 final_cltv_expiry_delta: 40,
9182 let network_graph = nodes[0].network_graph;
9183 let first_hops = nodes[0].node.list_usable_channels();
9184 let scorer = test_utils::TestScorer::with_penalty(0);
9185 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9186 let route = find_route(
9187 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9188 nodes[0].logger, &scorer, &random_seed_bytes
9191 let test_preimage = PaymentPreimage([42; 32]);
9192 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9193 check_added_monitors!(nodes[0], 1);
9194 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9195 assert_eq!(events.len(), 1);
9196 let event = events.pop().unwrap();
9197 let path = vec![&nodes[1]];
9198 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9199 claim_payment(&nodes[0], &path, test_preimage);
9203 fn test_double_partial_claim() {
9204 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9205 // time out, the sender resends only some of the MPP parts, then the user processes the
9206 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9208 let chanmon_cfgs = create_chanmon_cfgs(4);
9209 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9210 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9211 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9213 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9214 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9215 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9216 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9218 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9219 assert_eq!(route.paths.len(), 2);
9220 route.paths.sort_by(|path_a, _| {
9221 // Sort the path so that the path through nodes[1] comes first
9222 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9223 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9226 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9227 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9228 // amount of time to respond to.
9230 // Connect some blocks to time out the payment
9231 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9232 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9234 let failed_destinations = vec![
9235 HTLCDestination::FailedPayment { payment_hash },
9236 HTLCDestination::FailedPayment { payment_hash },
9238 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9240 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9242 // nodes[1] now retries one of the two paths...
9243 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9244 check_added_monitors!(nodes[0], 2);
9246 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9247 assert_eq!(events.len(), 2);
9248 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9250 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9251 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9252 nodes[3].node.claim_funds(payment_preimage);
9253 check_added_monitors!(nodes[3], 0);
9254 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9257 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9258 #[derive(Clone, Copy, PartialEq)]
9259 enum ExposureEvent {
9260 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9262 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9264 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9265 AtUpdateFeeOutbound,
9268 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9269 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9272 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9273 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9274 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9275 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9276 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9277 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9278 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9279 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9281 let chanmon_cfgs = create_chanmon_cfgs(2);
9282 let mut config = test_default_channel_config();
9283 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9284 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9285 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9286 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9288 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9289 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9290 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9291 open_channel.max_accepted_htlcs = 60;
9293 open_channel.dust_limit_satoshis = 546;
9295 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
9296 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9297 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
9299 let opt_anchors = false;
9301 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9304 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9305 chan.holder_dust_limit_satoshis = 546;
9309 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9310 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()));
9311 check_added_monitors!(nodes[1], 1);
9313 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()));
9314 check_added_monitors!(nodes[0], 1);
9316 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9317 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9318 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9320 let dust_buffer_feerate = {
9321 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9322 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9323 chan.get_dust_buffer_feerate(None) as u64
9325 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;
9326 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9328 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;
9329 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9331 let dust_htlc_on_counterparty_tx: u64 = 25;
9332 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9335 if dust_outbound_balance {
9336 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9337 // Outbound dust balance: 4372 sats
9338 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9339 for i in 0..dust_outbound_htlc_on_holder_tx {
9340 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9341 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); }
9344 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9345 // Inbound dust balance: 4372 sats
9346 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9347 for _ in 0..dust_inbound_htlc_on_holder_tx {
9348 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9352 if dust_outbound_balance {
9353 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9354 // Outbound dust balance: 5000 sats
9355 for i in 0..dust_htlc_on_counterparty_tx {
9356 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9357 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); }
9360 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9361 // Inbound dust balance: 5000 sats
9362 for _ in 0..dust_htlc_on_counterparty_tx {
9363 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9368 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9369 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9370 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 });
9371 let mut config = UserConfig::default();
9372 // With default dust exposure: 5000 sats
9374 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9375 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9376 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)));
9378 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)));
9380 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9381 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 });
9382 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9383 check_added_monitors!(nodes[1], 1);
9384 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9385 assert_eq!(events.len(), 1);
9386 let payment_event = SendEvent::from_event(events.remove(0));
9387 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9388 // With default dust exposure: 5000 sats
9390 // Outbound dust balance: 6399 sats
9391 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9392 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9393 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);
9395 // Outbound dust balance: 5200 sats
9396 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);
9398 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9399 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9400 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", ); }
9402 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9403 *feerate_lock = *feerate_lock * 10;
9405 nodes[0].node.timer_tick_occurred();
9406 check_added_monitors!(nodes[0], 1);
9407 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);
9410 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9411 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9412 added_monitors.clear();
9416 fn test_max_dust_htlc_exposure() {
9417 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9418 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9419 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9420 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9421 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9422 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9423 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9424 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9425 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9426 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9427 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9428 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9432 fn test_non_final_funding_tx() {
9433 let chanmon_cfgs = create_chanmon_cfgs(2);
9434 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9435 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9436 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9438 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9439 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9440 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
9441 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9442 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
9444 let best_height = nodes[0].node.best_block.read().unwrap().height();
9446 let chan_id = *nodes[0].network_chan_count.borrow();
9447 let events = nodes[0].node.get_and_clear_pending_events();
9448 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9449 assert_eq!(events.len(), 1);
9450 let mut tx = match events[0] {
9451 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9452 // Timelock the transaction _beyond_ the best client height + 2.
9453 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9454 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9457 _ => panic!("Unexpected event"),
9459 // Transaction should fail as it's evaluated as non-final for propagation.
9460 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9461 Err(APIError::APIMisuseError { err }) => {
9462 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9467 // However, transaction should be accepted if it's in a +2 headroom from best block.
9468 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9469 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9470 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());