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::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
23 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
24 use crate::ln::channel::{Channel, ChannelError};
25 use crate::ln::{chan_utils, onion_utils};
26 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
28 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use crate::ln::features::{ChannelFeatures, NodeFeatures};
31 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use crate::util::enforcing_trait_impls::EnforcingSigner;
33 use crate::util::test_utils;
34 use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::config::UserConfig;
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &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].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180 let mut sender_node_per_peer_lock;
181 let mut sender_node_peer_state_lock;
182 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183 chan.holder_selected_channel_reserve_satoshis = 0;
184 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
187 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193 if send_from_initiator {
194 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195 // Note that for outbound channels we have to consider the commitment tx fee and the
196 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197 // well as an additional HTLC.
198 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200 send_payment(&nodes[1], &[&nodes[0]], push_amt);
205 fn test_counterparty_no_reserve() {
206 do_test_counterparty_no_reserve(true);
207 do_test_counterparty_no_reserve(false);
211 fn test_async_inbound_update_fee() {
212 let chanmon_cfgs = create_chanmon_cfgs(2);
213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216 create_announced_chan_between_nodes(&nodes, 0, 1);
219 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
223 // send (1) commitment_signed -.
224 // <- update_add_htlc/commitment_signed
225 // send (2) RAA (awaiting remote revoke) -.
226 // (1) commitment_signed is delivered ->
227 // .- send (3) RAA (awaiting remote revoke)
228 // (2) RAA is delivered ->
229 // .- send (4) commitment_signed
230 // <- (3) RAA is delivered
231 // send (5) commitment_signed -.
232 // <- (4) commitment_signed is delivered
234 // (5) commitment_signed is delivered ->
236 // (6) RAA is delivered ->
238 // First nodes[0] generates an update_fee
240 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
243 nodes[0].node.timer_tick_occurred();
244 check_added_monitors!(nodes[0], 1);
246 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247 assert_eq!(events_0.len(), 1);
248 let (update_msg, commitment_signed) = match events_0[0] { // (1)
249 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250 (update_fee.as_ref(), commitment_signed)
252 _ => panic!("Unexpected event"),
255 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
260 check_added_monitors!(nodes[1], 1);
262 let payment_event = {
263 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
264 assert_eq!(events_1.len(), 1);
265 SendEvent::from_event(events_1.remove(0))
267 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
268 assert_eq!(payment_event.msgs.len(), 1);
270 // ...now when the messages get delivered everyone should be happy
271 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
272 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
273 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
274 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
275 check_added_monitors!(nodes[0], 1);
277 // deliver(1), generate (3):
278 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
279 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
280 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
281 check_added_monitors!(nodes[1], 1);
283 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
284 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
285 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
286 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
287 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
288 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
289 assert!(bs_update.update_fee.is_none()); // (4)
290 check_added_monitors!(nodes[1], 1);
292 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
293 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
294 assert!(as_update.update_add_htlcs.is_empty()); // (5)
295 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
296 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
297 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
298 assert!(as_update.update_fee.is_none()); // (5)
299 check_added_monitors!(nodes[0], 1);
301 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
302 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
303 // only (6) so get_event_msg's assert(len == 1) passes
304 check_added_monitors!(nodes[0], 1);
306 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
307 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
308 check_added_monitors!(nodes[1], 1);
310 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
311 check_added_monitors!(nodes[0], 1);
313 let events_2 = nodes[0].node.get_and_clear_pending_events();
314 assert_eq!(events_2.len(), 1);
316 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
317 _ => panic!("Unexpected event"),
320 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
321 check_added_monitors!(nodes[1], 1);
325 fn test_update_fee_unordered_raa() {
326 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
327 // crash in an earlier version of the update_fee patch)
328 let chanmon_cfgs = create_chanmon_cfgs(2);
329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
331 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
332 create_announced_chan_between_nodes(&nodes, 0, 1);
335 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
337 // First nodes[0] generates an update_fee
339 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
342 nodes[0].node.timer_tick_occurred();
343 check_added_monitors!(nodes[0], 1);
345 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
346 assert_eq!(events_0.len(), 1);
347 let update_msg = match events_0[0] { // (1)
348 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
351 _ => panic!("Unexpected event"),
354 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
356 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
357 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
358 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
359 check_added_monitors!(nodes[1], 1);
361 let payment_event = {
362 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
363 assert_eq!(events_1.len(), 1);
364 SendEvent::from_event(events_1.remove(0))
366 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
367 assert_eq!(payment_event.msgs.len(), 1);
369 // ...now when the messages get delivered everyone should be happy
370 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
371 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
372 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
373 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
374 check_added_monitors!(nodes[0], 1);
376 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
377 check_added_monitors!(nodes[1], 1);
379 // We can't continue, sadly, because our (1) now has a bogus signature
383 fn test_multi_flight_update_fee() {
384 let chanmon_cfgs = create_chanmon_cfgs(2);
385 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
386 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
387 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
388 create_announced_chan_between_nodes(&nodes, 0, 1);
391 // update_fee/commitment_signed ->
392 // .- send (1) RAA and (2) commitment_signed
393 // update_fee (never committed) ->
395 // We have to manually generate the above update_fee, it is allowed by the protocol but we
396 // don't track which updates correspond to which revoke_and_ack responses so we're in
397 // AwaitingRAA mode and will not generate the update_fee yet.
398 // <- (1) RAA delivered
399 // (3) is generated and send (4) CS -.
400 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
401 // know the per_commitment_point to use for it.
402 // <- (2) commitment_signed delivered
404 // B should send no response here
405 // (4) commitment_signed delivered ->
406 // <- RAA/commitment_signed delivered
409 // First nodes[0] generates an update_fee
412 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
413 initial_feerate = *feerate_lock;
414 *feerate_lock = initial_feerate + 20;
416 nodes[0].node.timer_tick_occurred();
417 check_added_monitors!(nodes[0], 1);
419 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
420 assert_eq!(events_0.len(), 1);
421 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
422 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
423 (update_fee.as_ref().unwrap(), commitment_signed)
425 _ => panic!("Unexpected event"),
428 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
429 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
430 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
431 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
432 check_added_monitors!(nodes[1], 1);
434 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
437 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
438 *feerate_lock = initial_feerate + 40;
440 nodes[0].node.timer_tick_occurred();
441 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
442 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
444 // Create the (3) update_fee message that nodes[0] will generate before it does...
445 let mut update_msg_2 = msgs::UpdateFee {
446 channel_id: update_msg_1.channel_id.clone(),
447 feerate_per_kw: (initial_feerate + 30) as u32,
450 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
452 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
454 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
456 // Deliver (1), generating (3) and (4)
457 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
458 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
459 check_added_monitors!(nodes[0], 1);
460 assert!(as_second_update.update_add_htlcs.is_empty());
461 assert!(as_second_update.update_fulfill_htlcs.is_empty());
462 assert!(as_second_update.update_fail_htlcs.is_empty());
463 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
464 // Check that the update_fee newly generated matches what we delivered:
465 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
466 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
468 // Deliver (2) commitment_signed
469 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
470 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
471 check_added_monitors!(nodes[0], 1);
472 // No commitment_signed so get_event_msg's assert(len == 1) passes
474 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
475 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
476 check_added_monitors!(nodes[1], 1);
479 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
480 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
481 check_added_monitors!(nodes[1], 1);
483 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
484 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
485 check_added_monitors!(nodes[0], 1);
487 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
488 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
489 // No commitment_signed so get_event_msg's assert(len == 1) passes
490 check_added_monitors!(nodes[0], 1);
492 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
493 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
494 check_added_monitors!(nodes[1], 1);
497 fn do_test_sanity_on_in_flight_opens(steps: u8) {
498 // Previously, we had issues deserializing channels when we hadn't connected the first block
499 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
500 // serialization round-trips and simply do steps towards opening a channel and then drop the
503 let chanmon_cfgs = create_chanmon_cfgs(2);
504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
506 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
508 if steps & 0b1000_0000 != 0{
510 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
513 connect_block(&nodes[0], &block);
514 connect_block(&nodes[1], &block);
517 if steps & 0x0f == 0 { return; }
518 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
519 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
521 if steps & 0x0f == 1 { return; }
522 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
523 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
525 if steps & 0x0f == 2 { return; }
526 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
528 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
530 if steps & 0x0f == 3 { return; }
531 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
532 check_added_monitors!(nodes[0], 0);
533 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
535 if steps & 0x0f == 4 { return; }
536 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
538 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
539 assert_eq!(added_monitors.len(), 1);
540 assert_eq!(added_monitors[0].0, funding_output);
541 added_monitors.clear();
543 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
545 if steps & 0x0f == 5 { return; }
546 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
548 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
549 assert_eq!(added_monitors.len(), 1);
550 assert_eq!(added_monitors[0].0, funding_output);
551 added_monitors.clear();
554 let events_4 = nodes[0].node.get_and_clear_pending_events();
555 assert_eq!(events_4.len(), 0);
557 if steps & 0x0f == 6 { return; }
558 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
560 if steps & 0x0f == 7 { return; }
561 confirm_transaction_at(&nodes[0], &tx, 2);
562 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
563 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
564 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
568 fn test_sanity_on_in_flight_opens() {
569 do_test_sanity_on_in_flight_opens(0);
570 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
571 do_test_sanity_on_in_flight_opens(1);
572 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(2);
574 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(3);
576 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(4);
578 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(5);
580 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(6);
582 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(7);
584 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(8);
586 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
590 fn test_update_fee_vanilla() {
591 let chanmon_cfgs = create_chanmon_cfgs(2);
592 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
593 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
594 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
595 create_announced_chan_between_nodes(&nodes, 0, 1);
598 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
601 nodes[0].node.timer_tick_occurred();
602 check_added_monitors!(nodes[0], 1);
604 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
605 assert_eq!(events_0.len(), 1);
606 let (update_msg, commitment_signed) = match events_0[0] {
607 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 } } => {
608 (update_fee.as_ref(), commitment_signed)
610 _ => panic!("Unexpected event"),
612 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
614 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
615 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
616 check_added_monitors!(nodes[1], 1);
618 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
619 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
620 check_added_monitors!(nodes[0], 1);
622 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
623 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
624 // No commitment_signed so get_event_msg's assert(len == 1) passes
625 check_added_monitors!(nodes[0], 1);
627 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
628 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
629 check_added_monitors!(nodes[1], 1);
633 fn test_update_fee_that_funder_cannot_afford() {
634 let chanmon_cfgs = create_chanmon_cfgs(2);
635 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
637 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
638 let channel_value = 5000;
640 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
641 let channel_id = chan.2;
642 let secp_ctx = Secp256k1::new();
643 let default_config = UserConfig::default();
644 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
646 let opt_anchors = false;
648 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
649 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
650 // calculate two different feerates here - the expected local limit as well as the expected
652 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;
653 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
655 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
656 *feerate_lock = feerate;
658 nodes[0].node.timer_tick_occurred();
659 check_added_monitors!(nodes[0], 1);
660 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
662 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
664 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
666 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
668 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
670 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
671 assert_eq!(commitment_tx.output.len(), 2);
672 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
673 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
674 actual_fee = channel_value - actual_fee;
675 assert_eq!(total_fee, actual_fee);
679 // Increment the feerate by a small constant, accounting for rounding errors
680 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
683 nodes[0].node.timer_tick_occurred();
684 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
685 check_added_monitors!(nodes[0], 0);
687 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
689 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
690 // needed to sign the new commitment tx and (2) sign the new commitment tx.
691 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
692 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
693 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
694 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
695 let chan_signer = local_chan.get_signer();
696 let pubkeys = chan_signer.pubkeys();
697 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
698 pubkeys.funding_pubkey)
700 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
701 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
702 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
703 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
704 let chan_signer = remote_chan.get_signer();
705 let pubkeys = chan_signer.pubkeys();
706 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
707 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
708 pubkeys.funding_pubkey)
711 // Assemble the set of keys we can use for signatures for our commitment_signed message.
712 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
713 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
716 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
717 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
718 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
719 let local_chan_signer = local_chan.get_signer();
720 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
721 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
722 INITIAL_COMMITMENT_NUMBER - 1,
724 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
725 opt_anchors, local_funding, remote_funding,
726 commit_tx_keys.clone(),
727 non_buffer_feerate + 4,
729 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
731 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
734 let commit_signed_msg = msgs::CommitmentSigned {
737 htlc_signatures: res.1
740 let update_fee = msgs::UpdateFee {
742 feerate_per_kw: non_buffer_feerate + 4,
745 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
747 //While producing the commitment_signed response after handling a received update_fee request the
748 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
749 //Should produce and error.
750 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
751 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
752 check_added_monitors!(nodes[1], 1);
753 check_closed_broadcast!(nodes[1], true);
754 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
758 fn test_update_fee_with_fundee_update_add_htlc() {
759 let chanmon_cfgs = create_chanmon_cfgs(2);
760 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
761 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
762 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
763 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
766 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
769 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
772 nodes[0].node.timer_tick_occurred();
773 check_added_monitors!(nodes[0], 1);
775 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
776 assert_eq!(events_0.len(), 1);
777 let (update_msg, commitment_signed) = match events_0[0] {
778 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 } } => {
779 (update_fee.as_ref(), commitment_signed)
781 _ => panic!("Unexpected event"),
783 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
784 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
785 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
786 check_added_monitors!(nodes[1], 1);
788 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
790 // nothing happens since node[1] is in AwaitingRemoteRevoke
791 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
793 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
794 assert_eq!(added_monitors.len(), 0);
795 added_monitors.clear();
797 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
798 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
799 // node[1] has nothing to do
801 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
802 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
803 check_added_monitors!(nodes[0], 1);
805 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
806 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
807 // No commitment_signed so get_event_msg's assert(len == 1) passes
808 check_added_monitors!(nodes[0], 1);
809 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
810 check_added_monitors!(nodes[1], 1);
811 // AwaitingRemoteRevoke ends here
813 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
814 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
815 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
816 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
817 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
818 assert_eq!(commitment_update.update_fee.is_none(), true);
820 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
821 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
822 check_added_monitors!(nodes[0], 1);
823 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
825 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
826 check_added_monitors!(nodes[1], 1);
827 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
829 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
830 check_added_monitors!(nodes[1], 1);
831 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
832 // No commitment_signed so get_event_msg's assert(len == 1) passes
834 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
835 check_added_monitors!(nodes[0], 1);
836 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
838 expect_pending_htlcs_forwardable!(nodes[0]);
840 let events = nodes[0].node.get_and_clear_pending_events();
841 assert_eq!(events.len(), 1);
843 Event::PaymentClaimable { .. } => { },
844 _ => panic!("Unexpected event"),
847 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
849 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
850 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
851 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
852 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
853 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
857 fn test_update_fee() {
858 let chanmon_cfgs = create_chanmon_cfgs(2);
859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
862 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
863 let channel_id = chan.2;
866 // (1) update_fee/commitment_signed ->
867 // <- (2) revoke_and_ack
868 // .- send (3) commitment_signed
869 // (4) update_fee/commitment_signed ->
870 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
871 // <- (3) commitment_signed delivered
872 // send (6) revoke_and_ack -.
873 // <- (5) deliver revoke_and_ack
874 // (6) deliver revoke_and_ack ->
875 // .- send (7) commitment_signed in response to (4)
876 // <- (7) deliver commitment_signed
879 // Create and deliver (1)...
882 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
883 feerate = *feerate_lock;
884 *feerate_lock = feerate + 20;
886 nodes[0].node.timer_tick_occurred();
887 check_added_monitors!(nodes[0], 1);
889 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
890 assert_eq!(events_0.len(), 1);
891 let (update_msg, commitment_signed) = match events_0[0] {
892 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 } } => {
893 (update_fee.as_ref(), commitment_signed)
895 _ => panic!("Unexpected event"),
897 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
899 // Generate (2) and (3):
900 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
901 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
902 check_added_monitors!(nodes[1], 1);
905 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
906 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
907 check_added_monitors!(nodes[0], 1);
909 // Create and deliver (4)...
911 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
912 *feerate_lock = feerate + 30;
914 nodes[0].node.timer_tick_occurred();
915 check_added_monitors!(nodes[0], 1);
916 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
917 assert_eq!(events_0.len(), 1);
918 let (update_msg, commitment_signed) = match events_0[0] {
919 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 } } => {
920 (update_fee.as_ref(), commitment_signed)
922 _ => panic!("Unexpected event"),
925 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
926 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
927 check_added_monitors!(nodes[1], 1);
929 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
930 // No commitment_signed so get_event_msg's assert(len == 1) passes
932 // Handle (3), creating (6):
933 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
934 check_added_monitors!(nodes[0], 1);
935 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
936 // No commitment_signed so get_event_msg's assert(len == 1) passes
939 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
940 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
941 check_added_monitors!(nodes[0], 1);
943 // Deliver (6), creating (7):
944 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
945 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
946 assert!(commitment_update.update_add_htlcs.is_empty());
947 assert!(commitment_update.update_fulfill_htlcs.is_empty());
948 assert!(commitment_update.update_fail_htlcs.is_empty());
949 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
950 assert!(commitment_update.update_fee.is_none());
951 check_added_monitors!(nodes[1], 1);
954 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
955 check_added_monitors!(nodes[0], 1);
956 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
957 // No commitment_signed so get_event_msg's assert(len == 1) passes
959 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
960 check_added_monitors!(nodes[1], 1);
961 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
963 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
964 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
965 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
966 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
967 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
971 fn fake_network_test() {
972 // Simple test which builds a network of ChannelManagers, connects them to each other, and
973 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
974 let chanmon_cfgs = create_chanmon_cfgs(4);
975 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
976 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
977 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
979 // Create some initial channels
980 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
981 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
982 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
984 // Rebalance the network a bit by relaying one payment through all the channels...
985 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
986 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
987 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
988 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
990 // Send some more payments
991 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
992 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
993 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
995 // Test failure packets
996 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
997 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
999 // Add a new channel that skips 3
1000 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1002 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1003 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1004 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1005 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1006 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1007 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1008 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010 // Do some rebalance loop payments, simultaneously
1011 let mut hops = Vec::with_capacity(3);
1012 hops.push(RouteHop {
1013 pubkey: nodes[2].node.get_our_node_id(),
1014 node_features: NodeFeatures::empty(),
1015 short_channel_id: chan_2.0.contents.short_channel_id,
1016 channel_features: ChannelFeatures::empty(),
1018 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1020 hops.push(RouteHop {
1021 pubkey: nodes[3].node.get_our_node_id(),
1022 node_features: NodeFeatures::empty(),
1023 short_channel_id: chan_3.0.contents.short_channel_id,
1024 channel_features: ChannelFeatures::empty(),
1026 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1028 hops.push(RouteHop {
1029 pubkey: nodes[1].node.get_our_node_id(),
1030 node_features: nodes[1].node.node_features(),
1031 short_channel_id: chan_4.0.contents.short_channel_id,
1032 channel_features: nodes[1].node.channel_features(),
1034 cltv_expiry_delta: TEST_FINAL_CLTV,
1036 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;
1037 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;
1038 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;
1040 let mut hops = Vec::with_capacity(3);
1041 hops.push(RouteHop {
1042 pubkey: nodes[3].node.get_our_node_id(),
1043 node_features: NodeFeatures::empty(),
1044 short_channel_id: chan_4.0.contents.short_channel_id,
1045 channel_features: ChannelFeatures::empty(),
1047 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1049 hops.push(RouteHop {
1050 pubkey: nodes[2].node.get_our_node_id(),
1051 node_features: NodeFeatures::empty(),
1052 short_channel_id: chan_3.0.contents.short_channel_id,
1053 channel_features: ChannelFeatures::empty(),
1055 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1057 hops.push(RouteHop {
1058 pubkey: nodes[1].node.get_our_node_id(),
1059 node_features: nodes[1].node.node_features(),
1060 short_channel_id: chan_2.0.contents.short_channel_id,
1061 channel_features: nodes[1].node.channel_features(),
1063 cltv_expiry_delta: TEST_FINAL_CLTV,
1065 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;
1066 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;
1067 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;
1069 // Claim the rebalances...
1070 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1071 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1073 // Close down the channels...
1074 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1075 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1076 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1077 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1078 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1079 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1080 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1081 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1082 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1083 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1084 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1089 fn holding_cell_htlc_counting() {
1090 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1091 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1092 // commitment dance rounds.
1093 let chanmon_cfgs = create_chanmon_cfgs(3);
1094 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1095 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1096 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1097 create_announced_chan_between_nodes(&nodes, 0, 1);
1098 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1100 let mut payments = Vec::new();
1101 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1102 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1103 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1104 payments.push((payment_preimage, payment_hash));
1106 check_added_monitors!(nodes[1], 1);
1108 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1109 assert_eq!(events.len(), 1);
1110 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1111 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1113 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1114 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1116 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1118 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 },
1119 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1120 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1121 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1124 // This should also be true if we try to forward a payment.
1125 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1127 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1128 check_added_monitors!(nodes[0], 1);
1131 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1132 assert_eq!(events.len(), 1);
1133 let payment_event = SendEvent::from_event(events.pop().unwrap());
1134 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1136 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1137 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1138 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1139 // fails), the second will process the resulting failure and fail the HTLC backward.
1140 expect_pending_htlcs_forwardable!(nodes[1]);
1141 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 }]);
1142 check_added_monitors!(nodes[1], 1);
1144 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1145 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1146 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1148 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1150 // Now forward all the pending HTLCs and claim them back
1151 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1152 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1153 check_added_monitors!(nodes[2], 1);
1155 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1156 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1157 check_added_monitors!(nodes[1], 1);
1158 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1160 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1161 check_added_monitors!(nodes[1], 1);
1162 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1164 for ref update in as_updates.update_add_htlcs.iter() {
1165 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1167 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1168 check_added_monitors!(nodes[2], 1);
1169 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1170 check_added_monitors!(nodes[2], 1);
1171 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1173 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1174 check_added_monitors!(nodes[1], 1);
1175 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1176 check_added_monitors!(nodes[1], 1);
1177 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1179 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1180 check_added_monitors!(nodes[2], 1);
1182 expect_pending_htlcs_forwardable!(nodes[2]);
1184 let events = nodes[2].node.get_and_clear_pending_events();
1185 assert_eq!(events.len(), payments.len());
1186 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1188 &Event::PaymentClaimable { ref payment_hash, .. } => {
1189 assert_eq!(*payment_hash, *hash);
1191 _ => panic!("Unexpected event"),
1195 for (preimage, _) in payments.drain(..) {
1196 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1199 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1203 fn duplicate_htlc_test() {
1204 // Test that we accept duplicate payment_hash HTLCs across the network and that
1205 // claiming/failing them are all separate and don't affect each other
1206 let chanmon_cfgs = create_chanmon_cfgs(6);
1207 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1208 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1209 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1211 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1212 create_announced_chan_between_nodes(&nodes, 0, 3);
1213 create_announced_chan_between_nodes(&nodes, 1, 3);
1214 create_announced_chan_between_nodes(&nodes, 2, 3);
1215 create_announced_chan_between_nodes(&nodes, 3, 4);
1216 create_announced_chan_between_nodes(&nodes, 3, 5);
1218 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1220 *nodes[0].network_payment_count.borrow_mut() -= 1;
1221 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1223 *nodes[0].network_payment_count.borrow_mut() -= 1;
1224 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1226 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1227 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1228 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1232 fn test_duplicate_htlc_different_direction_onchain() {
1233 // Test that ChannelMonitor doesn't generate 2 preimage txn
1234 // when we have 2 HTLCs with same preimage that go across a node
1235 // in opposite directions, even with the same payment secret.
1236 let chanmon_cfgs = create_chanmon_cfgs(2);
1237 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1238 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1239 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1241 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1244 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1246 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1248 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1249 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1250 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1252 // Provide preimage to node 0 by claiming payment
1253 nodes[0].node.claim_funds(payment_preimage);
1254 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1255 check_added_monitors!(nodes[0], 1);
1257 // Broadcast node 1 commitment txn
1258 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1260 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1261 let mut has_both_htlcs = 0; // check htlcs match ones committed
1262 for outp in remote_txn[0].output.iter() {
1263 if outp.value == 800_000 / 1000 {
1264 has_both_htlcs += 1;
1265 } else if outp.value == 900_000 / 1000 {
1266 has_both_htlcs += 1;
1269 assert_eq!(has_both_htlcs, 2);
1271 mine_transaction(&nodes[0], &remote_txn[0]);
1272 check_added_monitors!(nodes[0], 1);
1273 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1274 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1276 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1277 assert_eq!(claim_txn.len(), 3);
1279 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1280 check_spends!(claim_txn[1], remote_txn[0]);
1281 check_spends!(claim_txn[2], remote_txn[0]);
1282 let preimage_tx = &claim_txn[0];
1283 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1284 (&claim_txn[1], &claim_txn[2])
1286 (&claim_txn[2], &claim_txn[1])
1289 assert_eq!(preimage_tx.input.len(), 1);
1290 assert_eq!(preimage_bump_tx.input.len(), 1);
1292 assert_eq!(preimage_tx.input.len(), 1);
1293 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1294 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1296 assert_eq!(timeout_tx.input.len(), 1);
1297 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1298 check_spends!(timeout_tx, remote_txn[0]);
1299 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1301 let events = nodes[0].node.get_and_clear_pending_msg_events();
1302 assert_eq!(events.len(), 3);
1305 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1306 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1307 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1308 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1310 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, .. } } => {
1311 assert!(update_add_htlcs.is_empty());
1312 assert!(update_fail_htlcs.is_empty());
1313 assert_eq!(update_fulfill_htlcs.len(), 1);
1314 assert!(update_fail_malformed_htlcs.is_empty());
1315 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1317 _ => panic!("Unexpected event"),
1323 fn test_basic_channel_reserve() {
1324 let chanmon_cfgs = create_chanmon_cfgs(2);
1325 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1326 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1327 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1328 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1330 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1331 let channel_reserve = chan_stat.channel_reserve_msat;
1333 // The 2* and +1 are for the fee spike reserve.
1334 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1335 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1336 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1337 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1339 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1341 &APIError::ChannelUnavailable{ref err} =>
1342 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1343 _ => panic!("Unexpected error variant"),
1346 _ => panic!("Unexpected error variant"),
1348 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1349 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);
1351 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1355 fn test_fee_spike_violation_fails_htlc() {
1356 let chanmon_cfgs = create_chanmon_cfgs(2);
1357 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1358 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1359 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1360 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1362 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1363 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1364 let secp_ctx = Secp256k1::new();
1365 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1367 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1369 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1370 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1371 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1372 let msg = msgs::UpdateAddHTLC {
1375 amount_msat: htlc_msat,
1376 payment_hash: payment_hash,
1377 cltv_expiry: htlc_cltv,
1378 onion_routing_packet: onion_packet,
1381 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1383 // Now manually create the commitment_signed message corresponding to the update_add
1384 // nodes[0] just sent. In the code for construction of this message, "local" refers
1385 // to the sender of the message, and "remote" refers to the receiver.
1387 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1389 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1391 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1392 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1393 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1394 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1395 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1396 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1397 let chan_signer = local_chan.get_signer();
1398 // Make the signer believe we validated another commitment, so we can release the secret
1399 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1401 let pubkeys = chan_signer.pubkeys();
1402 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1403 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1404 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1405 chan_signer.pubkeys().funding_pubkey)
1407 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1408 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1409 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1410 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1411 let chan_signer = remote_chan.get_signer();
1412 let pubkeys = chan_signer.pubkeys();
1413 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1414 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1415 chan_signer.pubkeys().funding_pubkey)
1418 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1419 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1420 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1422 // Build the remote commitment transaction so we can sign it, and then later use the
1423 // signature for the commitment_signed message.
1424 let local_chan_balance = 1313;
1426 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1428 amount_msat: 3460001,
1429 cltv_expiry: htlc_cltv,
1431 transaction_output_index: Some(1),
1434 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1437 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1438 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1439 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1440 let local_chan_signer = local_chan.get_signer();
1441 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1445 local_chan.opt_anchors(), local_funding, remote_funding,
1446 commit_tx_keys.clone(),
1448 &mut vec![(accepted_htlc_info, ())],
1449 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1451 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1454 let commit_signed_msg = msgs::CommitmentSigned {
1457 htlc_signatures: res.1
1460 // Send the commitment_signed message to the nodes[1].
1461 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1462 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1464 // Send the RAA to nodes[1].
1465 let raa_msg = msgs::RevokeAndACK {
1467 per_commitment_secret: local_secret,
1468 next_per_commitment_point: next_local_point
1470 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1472 let events = nodes[1].node.get_and_clear_pending_msg_events();
1473 assert_eq!(events.len(), 1);
1474 // Make sure the HTLC failed in the way we expect.
1476 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1477 assert_eq!(update_fail_htlcs.len(), 1);
1478 update_fail_htlcs[0].clone()
1480 _ => panic!("Unexpected event"),
1482 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1483 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1485 check_added_monitors!(nodes[1], 2);
1489 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1490 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1491 // Set the fee rate for the channel very high, to the point where the fundee
1492 // sending any above-dust amount would result in a channel reserve violation.
1493 // In this test we check that we would be prevented from sending an HTLC in
1495 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1496 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1497 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1498 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1499 let default_config = UserConfig::default();
1500 let opt_anchors = false;
1502 let mut push_amt = 100_000_000;
1503 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1505 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1507 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1509 // Sending exactly enough to hit the reserve amount should be accepted
1510 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1511 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1514 // However one more HTLC should be significantly over the reserve amount and fail.
1515 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1516 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 },
1517 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1518 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1519 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);
1523 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1524 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1525 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1528 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1529 let default_config = UserConfig::default();
1530 let opt_anchors = false;
1532 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1533 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1534 // transaction fee with 0 HTLCs (183 sats)).
1535 let mut push_amt = 100_000_000;
1536 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1537 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1538 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1540 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1541 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1542 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1545 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1546 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1547 let secp_ctx = Secp256k1::new();
1548 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1549 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1550 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1551 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1552 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1553 let msg = msgs::UpdateAddHTLC {
1555 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1556 amount_msat: htlc_msat,
1557 payment_hash: payment_hash,
1558 cltv_expiry: htlc_cltv,
1559 onion_routing_packet: onion_packet,
1562 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1563 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1564 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);
1565 assert_eq!(nodes[0].node.list_channels().len(), 0);
1566 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1567 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1568 check_added_monitors!(nodes[0], 1);
1569 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() });
1573 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1574 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1575 // calculating our commitment transaction fee (this was previously broken).
1576 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1577 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1581 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1582 let default_config = UserConfig::default();
1583 let opt_anchors = false;
1585 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1586 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1587 // transaction fee with 0 HTLCs (183 sats)).
1588 let mut push_amt = 100_000_000;
1589 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1590 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1591 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1593 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1594 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1595 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1596 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1597 // commitment transaction fee.
1598 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1600 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1601 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1602 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1605 // One more than the dust amt should fail, however.
1606 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1607 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 },
1608 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1612 fn test_chan_init_feerate_unaffordability() {
1613 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1614 // channel reserve and feerate requirements.
1615 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1616 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1617 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1618 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1619 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1620 let default_config = UserConfig::default();
1621 let opt_anchors = false;
1623 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1625 let mut push_amt = 100_000_000;
1626 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1627 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1628 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1630 // During open, we don't have a "counterparty channel reserve" to check against, so that
1631 // requirement only comes into play on the open_channel handling side.
1632 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1633 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1634 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1635 open_channel_msg.push_msat += 1;
1636 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1638 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1639 assert_eq!(msg_events.len(), 1);
1640 match msg_events[0] {
1641 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1642 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1644 _ => panic!("Unexpected event"),
1649 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1650 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1651 // calculating our counterparty's commitment transaction fee (this was previously broken).
1652 let chanmon_cfgs = create_chanmon_cfgs(2);
1653 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1654 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1655 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1656 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1658 let payment_amt = 46000; // Dust amount
1659 // In the previous code, these first four payments would succeed.
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);
1665 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1666 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1673 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1674 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1675 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1679 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1680 let chanmon_cfgs = create_chanmon_cfgs(3);
1681 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1682 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1683 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1684 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1685 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1688 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1689 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1690 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1691 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1693 // Add a 2* and +1 for the fee spike reserve.
1694 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1695 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;
1696 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1698 // Add a pending HTLC.
1699 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1700 let payment_event_1 = {
1701 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1702 check_added_monitors!(nodes[0], 1);
1704 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1705 assert_eq!(events.len(), 1);
1706 SendEvent::from_event(events.remove(0))
1708 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1710 // Attempt to trigger a channel reserve violation --> payment failure.
1711 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1712 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;
1713 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1714 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1716 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1717 let secp_ctx = Secp256k1::new();
1718 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1719 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1720 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1721 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1722 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1723 let msg = msgs::UpdateAddHTLC {
1726 amount_msat: htlc_msat + 1,
1727 payment_hash: our_payment_hash_1,
1728 cltv_expiry: htlc_cltv,
1729 onion_routing_packet: onion_packet,
1732 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1733 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1734 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1735 assert_eq!(nodes[1].node.list_channels().len(), 1);
1736 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1737 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1738 check_added_monitors!(nodes[1], 1);
1739 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1743 fn test_inbound_outbound_capacity_is_not_zero() {
1744 let chanmon_cfgs = create_chanmon_cfgs(2);
1745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1747 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1748 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1749 let channels0 = node_chanmgrs[0].list_channels();
1750 let channels1 = node_chanmgrs[1].list_channels();
1751 let default_config = UserConfig::default();
1752 assert_eq!(channels0.len(), 1);
1753 assert_eq!(channels1.len(), 1);
1755 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1756 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1757 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1759 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1760 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1763 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1764 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1768 fn test_channel_reserve_holding_cell_htlcs() {
1769 let chanmon_cfgs = create_chanmon_cfgs(3);
1770 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1771 // When this test was written, the default base fee floated based on the HTLC count.
1772 // It is now fixed, so we simply set the fee to the expected value here.
1773 let mut config = test_default_channel_config();
1774 config.channel_config.forwarding_fee_base_msat = 239;
1775 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1776 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1777 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1778 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1780 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1781 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1783 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1784 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1786 macro_rules! expect_forward {
1788 let mut events = $node.node.get_and_clear_pending_msg_events();
1789 assert_eq!(events.len(), 1);
1790 check_added_monitors!($node, 1);
1791 let payment_event = SendEvent::from_event(events.remove(0));
1796 let feemsat = 239; // set above
1797 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1798 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1799 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1801 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1803 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1805 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1806 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1807 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);
1808 route.paths[0].last_mut().unwrap().fee_msat += 1;
1809 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1811 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 },
1812 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)));
1813 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1814 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);
1817 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1818 // nodes[0]'s wealth
1820 let amt_msat = recv_value_0 + total_fee_msat;
1821 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1822 // Also, ensure that each payment has enough to be over the dust limit to
1823 // ensure it'll be included in each commit tx fee calculation.
1824 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1825 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1826 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1830 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1831 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1832 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1833 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1834 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1836 let (stat01_, stat11_, stat12_, stat22_) = (
1837 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1838 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1839 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1840 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1843 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1844 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1845 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1846 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1847 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1850 // adding pending output.
1851 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1852 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1853 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1854 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1855 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1856 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1857 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1858 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1859 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1861 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1862 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1863 let amt_msat_1 = recv_value_1 + total_fee_msat;
1865 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);
1866 let payment_event_1 = {
1867 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1868 check_added_monitors!(nodes[0], 1);
1870 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1871 assert_eq!(events.len(), 1);
1872 SendEvent::from_event(events.remove(0))
1874 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1876 // channel reserve test with htlc pending output > 0
1877 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1879 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1880 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 },
1881 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1882 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1885 // split the rest to test holding cell
1886 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1887 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1888 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1889 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1891 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1892 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);
1895 // now see if they go through on both sides
1896 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);
1897 // but this will stuck in the holding cell
1898 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1899 check_added_monitors!(nodes[0], 0);
1900 let events = nodes[0].node.get_and_clear_pending_events();
1901 assert_eq!(events.len(), 0);
1903 // test with outbound holding cell amount > 0
1905 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1906 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 },
1907 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1908 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1909 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);
1912 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);
1913 // this will also stuck in the holding cell
1914 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1915 check_added_monitors!(nodes[0], 0);
1916 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1917 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1919 // flush the pending htlc
1920 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1921 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1922 check_added_monitors!(nodes[1], 1);
1924 // the pending htlc should be promoted to committed
1925 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1926 check_added_monitors!(nodes[0], 1);
1927 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1929 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1930 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1931 // No commitment_signed so get_event_msg's assert(len == 1) passes
1932 check_added_monitors!(nodes[0], 1);
1934 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1935 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1936 check_added_monitors!(nodes[1], 1);
1938 expect_pending_htlcs_forwardable!(nodes[1]);
1940 let ref payment_event_11 = expect_forward!(nodes[1]);
1941 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1942 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1944 expect_pending_htlcs_forwardable!(nodes[2]);
1945 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1947 // flush the htlcs in the holding cell
1948 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1949 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1951 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1952 expect_pending_htlcs_forwardable!(nodes[1]);
1954 let ref payment_event_3 = expect_forward!(nodes[1]);
1955 assert_eq!(payment_event_3.msgs.len(), 2);
1956 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1957 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1959 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1960 expect_pending_htlcs_forwardable!(nodes[2]);
1962 let events = nodes[2].node.get_and_clear_pending_events();
1963 assert_eq!(events.len(), 2);
1965 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1966 assert_eq!(our_payment_hash_21, *payment_hash);
1967 assert_eq!(recv_value_21, amount_msat);
1968 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1969 assert_eq!(via_channel_id, Some(chan_2.2));
1971 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1972 assert!(payment_preimage.is_none());
1973 assert_eq!(our_payment_secret_21, *payment_secret);
1975 _ => panic!("expected PaymentPurpose::InvoicePayment")
1978 _ => panic!("Unexpected event"),
1981 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1982 assert_eq!(our_payment_hash_22, *payment_hash);
1983 assert_eq!(recv_value_22, amount_msat);
1984 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1985 assert_eq!(via_channel_id, Some(chan_2.2));
1987 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1988 assert!(payment_preimage.is_none());
1989 assert_eq!(our_payment_secret_22, *payment_secret);
1991 _ => panic!("expected PaymentPurpose::InvoicePayment")
1994 _ => panic!("Unexpected event"),
1997 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1998 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1999 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2001 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2002 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2003 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2005 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2006 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);
2007 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2008 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2009 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2011 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2012 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2016 fn channel_reserve_in_flight_removes() {
2017 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2018 // can send to its counterparty, but due to update ordering, the other side may not yet have
2019 // considered those HTLCs fully removed.
2020 // This tests that we don't count HTLCs which will not be included in the next remote
2021 // commitment transaction towards the reserve value (as it implies no commitment transaction
2022 // will be generated which violates the remote reserve value).
2023 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2025 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2026 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2027 // you only consider the value of the first HTLC, it may not),
2028 // * start routing a third HTLC from A to B,
2029 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2030 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2031 // * deliver the first fulfill from B
2032 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2034 // * deliver A's response CS and RAA.
2035 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2036 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2037 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2038 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2039 let chanmon_cfgs = create_chanmon_cfgs(2);
2040 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2041 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2042 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2043 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2045 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2046 // Route the first two HTLCs.
2047 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2048 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2049 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2051 // Start routing the third HTLC (this is just used to get everyone in the right state).
2052 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2054 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2055 check_added_monitors!(nodes[0], 1);
2056 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2057 assert_eq!(events.len(), 1);
2058 SendEvent::from_event(events.remove(0))
2061 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2062 // initial fulfill/CS.
2063 nodes[1].node.claim_funds(payment_preimage_1);
2064 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2065 check_added_monitors!(nodes[1], 1);
2066 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2068 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2069 // remove the second HTLC when we send the HTLC back from B to A.
2070 nodes[1].node.claim_funds(payment_preimage_2);
2071 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2072 check_added_monitors!(nodes[1], 1);
2073 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2075 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2076 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2077 check_added_monitors!(nodes[0], 1);
2078 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2079 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2081 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2082 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2083 check_added_monitors!(nodes[1], 1);
2084 // B is already AwaitingRAA, so cant generate a CS here
2085 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2087 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2088 check_added_monitors!(nodes[1], 1);
2089 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2091 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2092 check_added_monitors!(nodes[0], 1);
2093 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2095 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2096 check_added_monitors!(nodes[1], 1);
2097 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2099 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2100 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2101 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2102 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2103 // on-chain as necessary).
2104 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2105 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2106 check_added_monitors!(nodes[0], 1);
2107 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2108 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2110 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2111 check_added_monitors!(nodes[1], 1);
2112 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2114 expect_pending_htlcs_forwardable!(nodes[1]);
2115 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2117 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2118 // resolve the second HTLC from A's point of view.
2119 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2120 check_added_monitors!(nodes[0], 1);
2121 expect_payment_path_successful!(nodes[0]);
2122 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2124 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2125 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2126 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2128 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2129 check_added_monitors!(nodes[1], 1);
2130 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2131 assert_eq!(events.len(), 1);
2132 SendEvent::from_event(events.remove(0))
2135 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2136 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2137 check_added_monitors!(nodes[0], 1);
2138 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2140 // Now just resolve all the outstanding messages/HTLCs for completeness...
2142 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2143 check_added_monitors!(nodes[1], 1);
2144 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2147 check_added_monitors!(nodes[1], 1);
2149 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2150 check_added_monitors!(nodes[0], 1);
2151 expect_payment_path_successful!(nodes[0]);
2152 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2154 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2155 check_added_monitors!(nodes[1], 1);
2156 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2158 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2159 check_added_monitors!(nodes[0], 1);
2161 expect_pending_htlcs_forwardable!(nodes[0]);
2162 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2164 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2165 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2169 fn channel_monitor_network_test() {
2170 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2171 // tests that ChannelMonitor is able to recover from various states.
2172 let chanmon_cfgs = create_chanmon_cfgs(5);
2173 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2174 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2175 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2177 // Create some initial channels
2178 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2179 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2180 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2181 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2183 // Make sure all nodes are at the same starting height
2184 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2185 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2186 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2187 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2188 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2190 // Rebalance the network a bit by relaying one payment through all the channels...
2191 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2192 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2193 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2196 // Simple case with no pending HTLCs:
2197 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2198 check_added_monitors!(nodes[1], 1);
2199 check_closed_broadcast!(nodes[1], true);
2201 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2202 assert_eq!(node_txn.len(), 1);
2203 mine_transaction(&nodes[0], &node_txn[0]);
2204 check_added_monitors!(nodes[0], 1);
2205 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2207 check_closed_broadcast!(nodes[0], true);
2208 assert_eq!(nodes[0].node.list_channels().len(), 0);
2209 assert_eq!(nodes[1].node.list_channels().len(), 1);
2210 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2211 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2213 // One pending HTLC is discarded by the force-close:
2214 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2216 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2217 // broadcasted until we reach the timelock time).
2218 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2219 check_closed_broadcast!(nodes[1], true);
2220 check_added_monitors!(nodes[1], 1);
2222 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2223 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2224 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2225 mine_transaction(&nodes[2], &node_txn[0]);
2226 check_added_monitors!(nodes[2], 1);
2227 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2229 check_closed_broadcast!(nodes[2], true);
2230 assert_eq!(nodes[1].node.list_channels().len(), 0);
2231 assert_eq!(nodes[2].node.list_channels().len(), 1);
2232 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2233 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2235 macro_rules! claim_funds {
2236 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2238 $node.node.claim_funds($preimage);
2239 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2240 check_added_monitors!($node, 1);
2242 let events = $node.node.get_and_clear_pending_msg_events();
2243 assert_eq!(events.len(), 1);
2245 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2246 assert!(update_add_htlcs.is_empty());
2247 assert!(update_fail_htlcs.is_empty());
2248 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2250 _ => panic!("Unexpected event"),
2256 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2257 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2258 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2259 check_added_monitors!(nodes[2], 1);
2260 check_closed_broadcast!(nodes[2], true);
2261 let node2_commitment_txid;
2263 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2264 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2265 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2266 node2_commitment_txid = node_txn[0].txid();
2268 // Claim the payment on nodes[3], giving it knowledge of the preimage
2269 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2270 mine_transaction(&nodes[3], &node_txn[0]);
2271 check_added_monitors!(nodes[3], 1);
2272 check_preimage_claim(&nodes[3], &node_txn);
2274 check_closed_broadcast!(nodes[3], true);
2275 assert_eq!(nodes[2].node.list_channels().len(), 0);
2276 assert_eq!(nodes[3].node.list_channels().len(), 1);
2277 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2278 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2280 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2281 // confusing us in the following tests.
2282 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2284 // One pending HTLC to time out:
2285 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2286 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2289 let (close_chan_update_1, close_chan_update_2) = {
2290 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2291 let events = nodes[3].node.get_and_clear_pending_msg_events();
2292 assert_eq!(events.len(), 2);
2293 let close_chan_update_1 = match events[0] {
2294 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2297 _ => panic!("Unexpected event"),
2300 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2301 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2303 _ => panic!("Unexpected event"),
2305 check_added_monitors!(nodes[3], 1);
2307 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2309 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2310 node_txn.retain(|tx| {
2311 if tx.input[0].previous_output.txid == node2_commitment_txid {
2317 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2319 // Claim the payment on nodes[4], giving it knowledge of the preimage
2320 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2322 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2323 let events = nodes[4].node.get_and_clear_pending_msg_events();
2324 assert_eq!(events.len(), 2);
2325 let close_chan_update_2 = match events[0] {
2326 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2329 _ => panic!("Unexpected event"),
2332 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2333 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2335 _ => panic!("Unexpected event"),
2337 check_added_monitors!(nodes[4], 1);
2338 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2340 mine_transaction(&nodes[4], &node_txn[0]);
2341 check_preimage_claim(&nodes[4], &node_txn);
2342 (close_chan_update_1, close_chan_update_2)
2344 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2345 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2346 assert_eq!(nodes[3].node.list_channels().len(), 0);
2347 assert_eq!(nodes[4].node.list_channels().len(), 0);
2349 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2350 ChannelMonitorUpdateStatus::Completed);
2351 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2352 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2356 fn test_justice_tx() {
2357 // Test justice txn built on revoked HTLC-Success tx, against both sides
2358 let mut alice_config = UserConfig::default();
2359 alice_config.channel_handshake_config.announced_channel = true;
2360 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2361 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2362 let mut bob_config = UserConfig::default();
2363 bob_config.channel_handshake_config.announced_channel = true;
2364 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2365 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2366 let user_cfgs = [Some(alice_config), Some(bob_config)];
2367 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2368 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2369 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2370 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2371 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2372 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2373 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2374 // Create some new channels:
2375 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2377 // A pending HTLC which will be revoked:
2378 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2379 // Get the will-be-revoked local txn from nodes[0]
2380 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2381 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2382 assert_eq!(revoked_local_txn[0].input.len(), 1);
2383 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2384 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2385 assert_eq!(revoked_local_txn[1].input.len(), 1);
2386 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2387 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2388 // Revoke the old state
2389 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2392 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2394 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2395 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2396 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2398 check_spends!(node_txn[0], revoked_local_txn[0]);
2399 node_txn.swap_remove(0);
2401 check_added_monitors!(nodes[1], 1);
2402 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2403 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2405 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2406 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2407 // Verify broadcast of revoked HTLC-timeout
2408 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2409 check_added_monitors!(nodes[0], 1);
2410 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2411 // Broadcast revoked HTLC-timeout on node 1
2412 mine_transaction(&nodes[1], &node_txn[1]);
2413 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2415 get_announce_close_broadcast_events(&nodes, 0, 1);
2417 assert_eq!(nodes[0].node.list_channels().len(), 0);
2418 assert_eq!(nodes[1].node.list_channels().len(), 0);
2420 // We test justice_tx build by A on B's revoked HTLC-Success tx
2421 // Create some new channels:
2422 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2424 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2428 // A pending HTLC which will be revoked:
2429 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2430 // Get the will-be-revoked local txn from B
2431 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2432 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2433 assert_eq!(revoked_local_txn[0].input.len(), 1);
2434 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2435 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2436 // Revoke the old state
2437 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2439 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2441 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2443 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2445 check_spends!(node_txn[0], revoked_local_txn[0]);
2446 node_txn.swap_remove(0);
2448 check_added_monitors!(nodes[0], 1);
2449 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2451 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2452 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2453 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2454 check_added_monitors!(nodes[1], 1);
2455 mine_transaction(&nodes[0], &node_txn[1]);
2456 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2457 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2459 get_announce_close_broadcast_events(&nodes, 0, 1);
2460 assert_eq!(nodes[0].node.list_channels().len(), 0);
2461 assert_eq!(nodes[1].node.list_channels().len(), 0);
2465 fn revoked_output_claim() {
2466 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2467 // transaction is broadcast by its counterparty
2468 let chanmon_cfgs = create_chanmon_cfgs(2);
2469 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2470 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2471 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2472 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2473 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2474 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2475 assert_eq!(revoked_local_txn.len(), 1);
2476 // Only output is the full channel value back to nodes[0]:
2477 assert_eq!(revoked_local_txn[0].output.len(), 1);
2478 // Send a payment through, updating everyone's latest commitment txn
2479 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2481 // Inform nodes[1] that nodes[0] broadcast a stale tx
2482 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2483 check_added_monitors!(nodes[1], 1);
2484 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2485 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2486 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2488 check_spends!(node_txn[0], revoked_local_txn[0]);
2490 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2491 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2492 get_announce_close_broadcast_events(&nodes, 0, 1);
2493 check_added_monitors!(nodes[0], 1);
2494 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2498 fn claim_htlc_outputs_shared_tx() {
2499 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2500 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2501 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2502 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2503 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2504 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2506 // Create some new channel:
2507 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2509 // Rebalance the network to generate htlc in the two directions
2510 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2511 // 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
2512 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2513 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2515 // Get the will-be-revoked local txn from node[0]
2516 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2517 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2518 assert_eq!(revoked_local_txn[0].input.len(), 1);
2519 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2520 assert_eq!(revoked_local_txn[1].input.len(), 1);
2521 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2522 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2523 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2525 //Revoke the old state
2526 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2529 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2530 check_added_monitors!(nodes[0], 1);
2531 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2532 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2533 check_added_monitors!(nodes[1], 1);
2534 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2535 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2536 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2538 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2539 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2541 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2542 check_spends!(node_txn[0], revoked_local_txn[0]);
2544 let mut witness_lens = BTreeSet::new();
2545 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2546 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2547 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2548 assert_eq!(witness_lens.len(), 3);
2549 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2550 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2551 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2553 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2554 // ANTI_REORG_DELAY confirmations.
2555 mine_transaction(&nodes[1], &node_txn[0]);
2556 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2557 expect_payment_failed!(nodes[1], payment_hash_2, false);
2559 get_announce_close_broadcast_events(&nodes, 0, 1);
2560 assert_eq!(nodes[0].node.list_channels().len(), 0);
2561 assert_eq!(nodes[1].node.list_channels().len(), 0);
2565 fn claim_htlc_outputs_single_tx() {
2566 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2567 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2568 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2571 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2573 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2575 // Rebalance the network to generate htlc in the two directions
2576 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2577 // 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
2578 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2579 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2580 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2582 // Get the will-be-revoked local txn from node[0]
2583 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2585 //Revoke the old state
2586 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2589 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2590 check_added_monitors!(nodes[0], 1);
2591 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2592 check_added_monitors!(nodes[1], 1);
2593 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2594 let mut events = nodes[0].node.get_and_clear_pending_events();
2595 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2596 match events.last().unwrap() {
2597 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2598 _ => panic!("Unexpected event"),
2601 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2602 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2604 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2605 assert_eq!(node_txn.len(), 7);
2607 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2608 assert_eq!(node_txn[0].input.len(), 1);
2609 check_spends!(node_txn[0], chan_1.3);
2610 assert_eq!(node_txn[1].input.len(), 1);
2611 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2612 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2613 check_spends!(node_txn[1], node_txn[0]);
2615 // Justice transactions are indices 2-3-4
2616 assert_eq!(node_txn[2].input.len(), 1);
2617 assert_eq!(node_txn[3].input.len(), 1);
2618 assert_eq!(node_txn[4].input.len(), 1);
2620 check_spends!(node_txn[2], revoked_local_txn[0]);
2621 check_spends!(node_txn[3], revoked_local_txn[0]);
2622 check_spends!(node_txn[4], revoked_local_txn[0]);
2624 let mut witness_lens = BTreeSet::new();
2625 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2626 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2627 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2628 assert_eq!(witness_lens.len(), 3);
2629 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2630 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2631 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2633 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2634 // ANTI_REORG_DELAY confirmations.
2635 mine_transaction(&nodes[1], &node_txn[2]);
2636 mine_transaction(&nodes[1], &node_txn[3]);
2637 mine_transaction(&nodes[1], &node_txn[4]);
2638 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2639 expect_payment_failed!(nodes[1], payment_hash_2, false);
2641 get_announce_close_broadcast_events(&nodes, 0, 1);
2642 assert_eq!(nodes[0].node.list_channels().len(), 0);
2643 assert_eq!(nodes[1].node.list_channels().len(), 0);
2647 fn test_htlc_on_chain_success() {
2648 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2649 // the preimage backward accordingly. So here we test that ChannelManager is
2650 // broadcasting the right event to other nodes in payment path.
2651 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2652 // A --------------------> B ----------------------> C (preimage)
2653 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2654 // commitment transaction was broadcast.
2655 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2657 // B should be able to claim via preimage if A then broadcasts its local tx.
2658 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2659 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2660 // PaymentSent event).
2662 let chanmon_cfgs = create_chanmon_cfgs(3);
2663 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2664 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2665 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2667 // Create some initial channels
2668 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2669 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2671 // Ensure all nodes are at the same height
2672 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2673 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2674 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2675 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2677 // Rebalance the network a bit by relaying one payment through all the channels...
2678 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2679 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2681 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2682 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2684 // Broadcast legit commitment tx from C on B's chain
2685 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2686 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2687 assert_eq!(commitment_tx.len(), 1);
2688 check_spends!(commitment_tx[0], chan_2.3);
2689 nodes[2].node.claim_funds(our_payment_preimage);
2690 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2691 nodes[2].node.claim_funds(our_payment_preimage_2);
2692 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2693 check_added_monitors!(nodes[2], 2);
2694 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2695 assert!(updates.update_add_htlcs.is_empty());
2696 assert!(updates.update_fail_htlcs.is_empty());
2697 assert!(updates.update_fail_malformed_htlcs.is_empty());
2698 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2700 mine_transaction(&nodes[2], &commitment_tx[0]);
2701 check_closed_broadcast!(nodes[2], true);
2702 check_added_monitors!(nodes[2], 1);
2703 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2704 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2705 assert_eq!(node_txn.len(), 2);
2706 check_spends!(node_txn[0], commitment_tx[0]);
2707 check_spends!(node_txn[1], commitment_tx[0]);
2708 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2709 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2711 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712 assert_eq!(node_txn[0].lock_time.0, 0);
2713 assert_eq!(node_txn[1].lock_time.0, 0);
2715 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2716 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2717 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2718 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2720 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2721 assert_eq!(added_monitors.len(), 1);
2722 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2723 added_monitors.clear();
2725 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2726 assert_eq!(forwarded_events.len(), 3);
2727 match forwarded_events[0] {
2728 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2729 _ => panic!("Unexpected event"),
2731 let chan_id = Some(chan_1.2);
2732 match forwarded_events[1] {
2733 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2734 assert_eq!(fee_earned_msat, Some(1000));
2735 assert_eq!(prev_channel_id, chan_id);
2736 assert_eq!(claim_from_onchain_tx, true);
2737 assert_eq!(next_channel_id, Some(chan_2.2));
2741 match forwarded_events[2] {
2742 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2743 assert_eq!(fee_earned_msat, Some(1000));
2744 assert_eq!(prev_channel_id, chan_id);
2745 assert_eq!(claim_from_onchain_tx, true);
2746 assert_eq!(next_channel_id, Some(chan_2.2));
2750 let events = nodes[1].node.get_and_clear_pending_msg_events();
2752 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2753 assert_eq!(added_monitors.len(), 2);
2754 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2755 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2756 added_monitors.clear();
2758 assert_eq!(events.len(), 3);
2760 let (nodes_2_event, events) = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &events);
2761 let (nodes_0_event, events) = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &events);
2763 match nodes_2_event {
2764 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2765 _ => panic!("Unexpected event"),
2768 match nodes_0_event {
2769 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, .. } } => {
2770 assert!(update_add_htlcs.is_empty());
2771 assert!(update_fail_htlcs.is_empty());
2772 assert_eq!(update_fulfill_htlcs.len(), 1);
2773 assert!(update_fail_malformed_htlcs.is_empty());
2774 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2776 _ => panic!("Unexpected event"),
2779 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2781 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2782 _ => panic!("Unexpected event"),
2785 macro_rules! check_tx_local_broadcast {
2786 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2787 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2788 assert_eq!(node_txn.len(), 2);
2789 // Node[1]: 2 * HTLC-timeout tx
2790 // Node[0]: 2 * HTLC-timeout tx
2791 check_spends!(node_txn[0], $commitment_tx);
2792 check_spends!(node_txn[1], $commitment_tx);
2793 assert_ne!(node_txn[0].lock_time.0, 0);
2794 assert_ne!(node_txn[1].lock_time.0, 0);
2796 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2797 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2798 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2799 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2801 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2802 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2803 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2804 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2809 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2810 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2812 // Broadcast legit commitment tx from A on B's chain
2813 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2814 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2815 check_spends!(node_a_commitment_tx[0], chan_1.3);
2816 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2817 check_closed_broadcast!(nodes[1], true);
2818 check_added_monitors!(nodes[1], 1);
2819 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2820 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2821 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2822 let commitment_spend =
2823 if node_txn.len() == 1 {
2826 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2827 // FullBlockViaListen
2828 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2829 check_spends!(node_txn[1], commitment_tx[0]);
2830 check_spends!(node_txn[2], commitment_tx[0]);
2831 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2834 check_spends!(node_txn[0], commitment_tx[0]);
2835 check_spends!(node_txn[1], commitment_tx[0]);
2836 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2841 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2842 assert_eq!(commitment_spend.input.len(), 2);
2843 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845 assert_eq!(commitment_spend.lock_time.0, 0);
2846 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
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]);
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);
2897 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
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();
2930 assert_eq!(node_txn.len(), 0);
2932 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2933 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2934 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2935 mine_transaction(&nodes[1], &commitment_tx[0]);
2936 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2939 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2940 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2942 check_spends!(node_txn[2], commitment_tx[0]);
2943 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2945 check_spends!(node_txn[0], chan_2.3);
2946 check_spends!(node_txn[1], node_txn[0]);
2947 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2948 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2950 timeout_tx = node_txn[2].clone();
2954 mine_transaction(&nodes[1], &timeout_tx);
2955 check_added_monitors!(nodes[1], 1);
2956 check_closed_broadcast!(nodes[1], true);
2958 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2960 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 }]);
2961 check_added_monitors!(nodes[1], 1);
2962 let events = nodes[1].node.get_and_clear_pending_msg_events();
2963 assert_eq!(events.len(), 1);
2965 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, .. } } => {
2966 assert!(update_add_htlcs.is_empty());
2967 assert!(!update_fail_htlcs.is_empty());
2968 assert!(update_fulfill_htlcs.is_empty());
2969 assert!(update_fail_malformed_htlcs.is_empty());
2970 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2972 _ => panic!("Unexpected event"),
2975 // Broadcast legit commitment tx from B on A's chain
2976 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2977 check_spends!(commitment_tx[0], chan_1.3);
2979 mine_transaction(&nodes[0], &commitment_tx[0]);
2980 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2982 check_closed_broadcast!(nodes[0], true);
2983 check_added_monitors!(nodes[0], 1);
2984 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2985 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2986 assert_eq!(node_txn.len(), 1);
2987 check_spends!(node_txn[0], commitment_tx[0]);
2988 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2992 fn test_htlc_on_chain_timeout() {
2993 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2994 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2995 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2999 fn test_simple_commitment_revoked_fail_backward() {
3000 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3001 // and fail backward accordingly.
3003 let chanmon_cfgs = create_chanmon_cfgs(3);
3004 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3005 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3006 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3008 // Create some initial channels
3009 create_announced_chan_between_nodes(&nodes, 0, 1);
3010 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3012 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3013 // Get the will-be-revoked local txn from nodes[2]
3014 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3015 // Revoke the old state
3016 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3018 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3020 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3021 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3022 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3023 check_added_monitors!(nodes[1], 1);
3024 check_closed_broadcast!(nodes[1], true);
3026 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 }]);
3027 check_added_monitors!(nodes[1], 1);
3028 let events = nodes[1].node.get_and_clear_pending_msg_events();
3029 assert_eq!(events.len(), 1);
3031 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, .. } } => {
3032 assert!(update_add_htlcs.is_empty());
3033 assert_eq!(update_fail_htlcs.len(), 1);
3034 assert!(update_fulfill_htlcs.is_empty());
3035 assert!(update_fail_malformed_htlcs.is_empty());
3036 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3038 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3039 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3040 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3042 _ => panic!("Unexpected event"),
3046 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3047 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3048 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3049 // commitment transaction anymore.
3050 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3051 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3052 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3053 // technically disallowed and we should probably handle it reasonably.
3054 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3055 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3057 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3058 // commitment_signed (implying it will be in the latest remote commitment transaction).
3059 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3060 // and once they revoke the previous commitment transaction (allowing us to send a new
3061 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3062 let chanmon_cfgs = create_chanmon_cfgs(3);
3063 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3064 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3065 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3067 // Create some initial channels
3068 create_announced_chan_between_nodes(&nodes, 0, 1);
3069 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3071 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 });
3072 // Get the will-be-revoked local txn from nodes[2]
3073 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3074 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3075 // Revoke the old state
3076 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3078 let value = if use_dust {
3079 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3080 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3081 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3082 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3085 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3086 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3087 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3089 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3090 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3091 check_added_monitors!(nodes[2], 1);
3092 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3093 assert!(updates.update_add_htlcs.is_empty());
3094 assert!(updates.update_fulfill_htlcs.is_empty());
3095 assert!(updates.update_fail_malformed_htlcs.is_empty());
3096 assert_eq!(updates.update_fail_htlcs.len(), 1);
3097 assert!(updates.update_fee.is_none());
3098 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3099 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3100 // Drop the last RAA from 3 -> 2
3102 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3103 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3104 check_added_monitors!(nodes[2], 1);
3105 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3106 assert!(updates.update_add_htlcs.is_empty());
3107 assert!(updates.update_fulfill_htlcs.is_empty());
3108 assert!(updates.update_fail_malformed_htlcs.is_empty());
3109 assert_eq!(updates.update_fail_htlcs.len(), 1);
3110 assert!(updates.update_fee.is_none());
3111 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3112 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3113 check_added_monitors!(nodes[1], 1);
3114 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3115 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3116 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3117 check_added_monitors!(nodes[2], 1);
3119 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3120 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3121 check_added_monitors!(nodes[2], 1);
3122 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3123 assert!(updates.update_add_htlcs.is_empty());
3124 assert!(updates.update_fulfill_htlcs.is_empty());
3125 assert!(updates.update_fail_malformed_htlcs.is_empty());
3126 assert_eq!(updates.update_fail_htlcs.len(), 1);
3127 assert!(updates.update_fee.is_none());
3128 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3129 // At this point first_payment_hash has dropped out of the latest two commitment
3130 // transactions that nodes[1] is tracking...
3131 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3132 check_added_monitors!(nodes[1], 1);
3133 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3134 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3135 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3136 check_added_monitors!(nodes[2], 1);
3138 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3139 // on nodes[2]'s RAA.
3140 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3141 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3142 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3143 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3144 check_added_monitors!(nodes[1], 0);
3147 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3148 // One monitor for the new revocation preimage, no second on as we won't generate a new
3149 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3150 check_added_monitors!(nodes[1], 1);
3151 let events = nodes[1].node.get_and_clear_pending_events();
3152 assert_eq!(events.len(), 2);
3154 Event::PendingHTLCsForwardable { .. } => { },
3155 _ => panic!("Unexpected event"),
3158 Event::HTLCHandlingFailed { .. } => { },
3159 _ => panic!("Unexpected event"),
3161 // Deliberately don't process the pending fail-back so they all fail back at once after
3162 // block connection just like the !deliver_bs_raa case
3165 let mut failed_htlcs = HashSet::new();
3166 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3168 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3169 check_added_monitors!(nodes[1], 1);
3170 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3172 let events = nodes[1].node.get_and_clear_pending_events();
3173 assert_eq!(events.len(), if deliver_bs_raa { 2 + nodes.len() - 1 } else { 3 + nodes.len() });
3175 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3176 _ => panic!("Unexepected event"),
3179 Event::PaymentPathFailed { ref payment_hash, .. } => {
3180 assert_eq!(*payment_hash, fourth_payment_hash);
3182 _ => panic!("Unexpected event"),
3184 if !deliver_bs_raa {
3186 Event::PendingHTLCsForwardable { .. } => { },
3187 _ => panic!("Unexpected event"),
3189 nodes[1].node.abandon_payment(PaymentId(fourth_payment_hash.0));
3190 let payment_failed_events = nodes[1].node.get_and_clear_pending_events();
3191 assert_eq!(payment_failed_events.len(), 1);
3192 match payment_failed_events[0] {
3193 Event::PaymentFailed { ref payment_hash, .. } => {
3194 assert_eq!(*payment_hash, fourth_payment_hash);
3196 _ => panic!("Unexpected event"),
3199 nodes[1].node.process_pending_htlc_forwards();
3200 check_added_monitors!(nodes[1], 1);
3202 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3203 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3205 let events = if deliver_bs_raa {
3206 let (nodes_2_event, events) = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &events);
3207 match nodes_2_event {
3208 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, .. } } => {
3209 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3210 assert_eq!(update_add_htlcs.len(), 1);
3211 assert!(update_fulfill_htlcs.is_empty());
3212 assert!(update_fail_htlcs.is_empty());
3213 assert!(update_fail_malformed_htlcs.is_empty());
3215 _ => panic!("Unexpected event"),
3220 let (nodes_2_event, events) = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &events);
3221 match nodes_2_event {
3222 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3223 assert_eq!(channel_id, chan_2.2);
3224 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3226 _ => panic!("Unexpected event"),
3229 let (nodes_0_event, events) = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &events);
3230 match nodes_0_event {
3231 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, .. } } => {
3232 assert!(update_add_htlcs.is_empty());
3233 assert_eq!(update_fail_htlcs.len(), 3);
3234 assert!(update_fulfill_htlcs.is_empty());
3235 assert!(update_fail_malformed_htlcs.is_empty());
3236 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3238 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3239 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3240 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3242 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3244 let events = nodes[0].node.get_and_clear_pending_events();
3245 assert_eq!(events.len(), 3);
3247 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3248 assert!(failed_htlcs.insert(payment_hash.0));
3249 // If we delivered B's RAA we got an unknown preimage error, not something
3250 // that we should update our routing table for.
3251 if !deliver_bs_raa {
3252 assert!(network_update.is_some());
3255 _ => panic!("Unexpected event"),
3258 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3259 assert!(failed_htlcs.insert(payment_hash.0));
3260 assert!(network_update.is_some());
3262 _ => panic!("Unexpected event"),
3265 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3266 assert!(failed_htlcs.insert(payment_hash.0));
3267 assert!(network_update.is_some());
3269 _ => panic!("Unexpected event"),
3272 _ => panic!("Unexpected event"),
3275 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3277 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3278 _ => panic!("Unexpected event"),
3281 assert!(failed_htlcs.contains(&first_payment_hash.0));
3282 assert!(failed_htlcs.contains(&second_payment_hash.0));
3283 assert!(failed_htlcs.contains(&third_payment_hash.0));
3287 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3288 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3289 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3290 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3291 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3295 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3296 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3297 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3298 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3299 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3303 fn fail_backward_pending_htlc_upon_channel_failure() {
3304 let chanmon_cfgs = create_chanmon_cfgs(2);
3305 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3306 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3307 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3308 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3310 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3312 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3313 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3314 check_added_monitors!(nodes[0], 1);
3316 let payment_event = {
3317 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3318 assert_eq!(events.len(), 1);
3319 SendEvent::from_event(events.remove(0))
3321 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3322 assert_eq!(payment_event.msgs.len(), 1);
3325 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3326 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3328 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3329 check_added_monitors!(nodes[0], 0);
3331 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3334 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3336 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3338 let secp_ctx = Secp256k1::new();
3339 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3340 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3341 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3342 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3343 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3345 // Send a 0-msat update_add_htlc to fail the channel.
3346 let update_add_htlc = msgs::UpdateAddHTLC {
3352 onion_routing_packet,
3354 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3356 let events = nodes[0].node.get_and_clear_pending_events();
3357 assert_eq!(events.len(), 2);
3358 // Check that Alice fails backward the pending HTLC from the second payment.
3360 Event::PaymentPathFailed { payment_hash, .. } => {
3361 assert_eq!(payment_hash, failed_payment_hash);
3363 _ => panic!("Unexpected event"),
3366 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3367 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3369 _ => panic!("Unexpected event {:?}", events[1]),
3371 check_closed_broadcast!(nodes[0], true);
3372 check_added_monitors!(nodes[0], 1);
3376 fn test_htlc_ignore_latest_remote_commitment() {
3377 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3378 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3379 let chanmon_cfgs = create_chanmon_cfgs(2);
3380 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3381 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3382 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3383 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3384 // We rely on the ability to connect a block redundantly, which isn't allowed via
3385 // `chain::Listen`, so we never run the test if we randomly get assigned that
3389 create_announced_chan_between_nodes(&nodes, 0, 1);
3391 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3392 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3393 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3394 check_closed_broadcast!(nodes[0], true);
3395 check_added_monitors!(nodes[0], 1);
3396 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3398 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3399 assert_eq!(node_txn.len(), 3);
3400 assert_eq!(node_txn[0], node_txn[1]);
3402 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3403 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3404 check_closed_broadcast!(nodes[1], true);
3405 check_added_monitors!(nodes[1], 1);
3406 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3408 // Duplicate the connect_block call since this may happen due to other listeners
3409 // registering new transactions
3410 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3414 fn test_force_close_fail_back() {
3415 // Check which HTLCs are failed-backwards on channel force-closure
3416 let chanmon_cfgs = create_chanmon_cfgs(3);
3417 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3418 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3419 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3420 create_announced_chan_between_nodes(&nodes, 0, 1);
3421 create_announced_chan_between_nodes(&nodes, 1, 2);
3423 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3425 let mut payment_event = {
3426 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3427 check_added_monitors!(nodes[0], 1);
3429 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3430 assert_eq!(events.len(), 1);
3431 SendEvent::from_event(events.remove(0))
3434 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3435 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3437 expect_pending_htlcs_forwardable!(nodes[1]);
3439 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3440 assert_eq!(events_2.len(), 1);
3441 payment_event = SendEvent::from_event(events_2.remove(0));
3442 assert_eq!(payment_event.msgs.len(), 1);
3444 check_added_monitors!(nodes[1], 1);
3445 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3446 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3447 check_added_monitors!(nodes[2], 1);
3448 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3450 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3451 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3452 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3454 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3455 check_closed_broadcast!(nodes[2], true);
3456 check_added_monitors!(nodes[2], 1);
3457 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3459 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3460 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3461 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3462 // back to nodes[1] upon timeout otherwise.
3463 assert_eq!(node_txn.len(), 1);
3467 mine_transaction(&nodes[1], &tx);
3469 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3470 check_closed_broadcast!(nodes[1], true);
3471 check_added_monitors!(nodes[1], 1);
3472 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3474 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3476 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3477 .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);
3479 mine_transaction(&nodes[2], &tx);
3480 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3481 assert_eq!(node_txn.len(), 1);
3482 assert_eq!(node_txn[0].input.len(), 1);
3483 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3484 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3485 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3487 check_spends!(node_txn[0], tx);
3491 fn test_dup_events_on_peer_disconnect() {
3492 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3493 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3494 // as we used to generate the event immediately upon receipt of the payment preimage in the
3495 // update_fulfill_htlc message.
3497 let chanmon_cfgs = create_chanmon_cfgs(2);
3498 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3499 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3500 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3501 create_announced_chan_between_nodes(&nodes, 0, 1);
3503 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3505 nodes[1].node.claim_funds(payment_preimage);
3506 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3507 check_added_monitors!(nodes[1], 1);
3508 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3509 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3510 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3512 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3513 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3515 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3516 expect_payment_path_successful!(nodes[0]);
3520 fn test_peer_disconnected_before_funding_broadcasted() {
3521 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3522 // before the funding transaction has been broadcasted.
3523 let chanmon_cfgs = create_chanmon_cfgs(2);
3524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3526 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3528 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3529 // broadcasted, even though it's created by `nodes[0]`.
3530 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();
3531 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3532 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3533 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3534 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3536 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3537 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3539 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3541 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3542 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3544 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3545 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3548 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3551 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3552 // disconnected before the funding transaction was broadcasted.
3553 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3554 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3556 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3557 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3561 fn test_simple_peer_disconnect() {
3562 // Test that we can reconnect when there are no lost messages
3563 let chanmon_cfgs = create_chanmon_cfgs(3);
3564 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3565 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3566 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3567 create_announced_chan_between_nodes(&nodes, 0, 1);
3568 create_announced_chan_between_nodes(&nodes, 1, 2);
3570 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3571 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3572 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3574 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3575 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3576 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3577 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3579 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3580 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3581 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3583 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3584 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3585 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3586 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3588 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3589 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3591 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3592 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3594 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3596 let events = nodes[0].node.get_and_clear_pending_events();
3597 assert_eq!(events.len(), 3);
3599 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3600 assert_eq!(payment_preimage, payment_preimage_3);
3601 assert_eq!(payment_hash, payment_hash_3);
3603 _ => panic!("Unexpected event"),
3606 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3607 assert_eq!(payment_hash, payment_hash_5);
3608 assert!(payment_failed_permanently);
3610 _ => panic!("Unexpected event"),
3613 Event::PaymentPathSuccessful { .. } => {},
3614 _ => panic!("Unexpected event"),
3618 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3619 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3622 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3623 // Test that we can reconnect when in-flight HTLC updates get dropped
3624 let chanmon_cfgs = create_chanmon_cfgs(2);
3625 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3626 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3627 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3629 let mut as_channel_ready = None;
3630 let channel_id = if messages_delivered == 0 {
3631 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3632 as_channel_ready = Some(channel_ready);
3633 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3634 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3635 // it before the channel_reestablish message.
3638 create_announced_chan_between_nodes(&nodes, 0, 1).2
3641 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3643 let payment_event = {
3644 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3645 check_added_monitors!(nodes[0], 1);
3647 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3648 assert_eq!(events.len(), 1);
3649 SendEvent::from_event(events.remove(0))
3651 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3653 if messages_delivered < 2 {
3654 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3656 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3657 if messages_delivered >= 3 {
3658 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3659 check_added_monitors!(nodes[1], 1);
3660 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3662 if messages_delivered >= 4 {
3663 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3664 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3665 check_added_monitors!(nodes[0], 1);
3667 if messages_delivered >= 5 {
3668 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3669 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3670 // No commitment_signed so get_event_msg's assert(len == 1) passes
3671 check_added_monitors!(nodes[0], 1);
3673 if messages_delivered >= 6 {
3674 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3675 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3676 check_added_monitors!(nodes[1], 1);
3683 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3684 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3685 if messages_delivered < 3 {
3686 if simulate_broken_lnd {
3687 // lnd has a long-standing bug where they send a channel_ready prior to a
3688 // channel_reestablish if you reconnect prior to channel_ready time.
3690 // Here we simulate that behavior, delivering a channel_ready immediately on
3691 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3692 // in `reconnect_nodes` but we currently don't fail based on that.
3694 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3695 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3697 // Even if the channel_ready messages get exchanged, as long as nothing further was
3698 // received on either side, both sides will need to resend them.
3699 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3700 } else if messages_delivered == 3 {
3701 // nodes[0] still wants its RAA + commitment_signed
3702 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3703 } else if messages_delivered == 4 {
3704 // nodes[0] still wants its commitment_signed
3705 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3706 } else if messages_delivered == 5 {
3707 // nodes[1] still wants its final RAA
3708 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3709 } else if messages_delivered == 6 {
3710 // Everything was delivered...
3711 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3714 let events_1 = nodes[1].node.get_and_clear_pending_events();
3715 if messages_delivered == 0 {
3716 assert_eq!(events_1.len(), 2);
3718 Event::ChannelReady { .. } => { },
3719 _ => panic!("Unexpected event"),
3722 Event::PendingHTLCsForwardable { .. } => { },
3723 _ => panic!("Unexpected event"),
3726 assert_eq!(events_1.len(), 1);
3728 Event::PendingHTLCsForwardable { .. } => { },
3729 _ => panic!("Unexpected event"),
3733 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3734 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3735 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3737 nodes[1].node.process_pending_htlc_forwards();
3739 let events_2 = nodes[1].node.get_and_clear_pending_events();
3740 assert_eq!(events_2.len(), 1);
3742 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3743 assert_eq!(payment_hash_1, *payment_hash);
3744 assert_eq!(amount_msat, 1_000_000);
3745 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3746 assert_eq!(via_channel_id, Some(channel_id));
3748 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3749 assert!(payment_preimage.is_none());
3750 assert_eq!(payment_secret_1, *payment_secret);
3752 _ => panic!("expected PaymentPurpose::InvoicePayment")
3755 _ => panic!("Unexpected event"),
3758 nodes[1].node.claim_funds(payment_preimage_1);
3759 check_added_monitors!(nodes[1], 1);
3760 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3762 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3763 assert_eq!(events_3.len(), 1);
3764 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3765 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3766 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3767 assert!(updates.update_add_htlcs.is_empty());
3768 assert!(updates.update_fail_htlcs.is_empty());
3769 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3770 assert!(updates.update_fail_malformed_htlcs.is_empty());
3771 assert!(updates.update_fee.is_none());
3772 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3774 _ => panic!("Unexpected event"),
3777 if messages_delivered >= 1 {
3778 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3780 let events_4 = nodes[0].node.get_and_clear_pending_events();
3781 assert_eq!(events_4.len(), 1);
3783 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3784 assert_eq!(payment_preimage_1, *payment_preimage);
3785 assert_eq!(payment_hash_1, *payment_hash);
3787 _ => panic!("Unexpected event"),
3790 if messages_delivered >= 2 {
3791 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3792 check_added_monitors!(nodes[0], 1);
3793 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3795 if messages_delivered >= 3 {
3796 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3797 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3798 check_added_monitors!(nodes[1], 1);
3800 if messages_delivered >= 4 {
3801 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3802 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3803 // No commitment_signed so get_event_msg's assert(len == 1) passes
3804 check_added_monitors!(nodes[1], 1);
3806 if messages_delivered >= 5 {
3807 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3808 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3809 check_added_monitors!(nodes[0], 1);
3816 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3817 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3818 if messages_delivered < 2 {
3819 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820 if messages_delivered < 1 {
3821 expect_payment_sent!(nodes[0], payment_preimage_1);
3823 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3825 } else if messages_delivered == 2 {
3826 // nodes[0] still wants its RAA + commitment_signed
3827 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3828 } else if messages_delivered == 3 {
3829 // nodes[0] still wants its commitment_signed
3830 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3831 } else if messages_delivered == 4 {
3832 // nodes[1] still wants its final RAA
3833 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3834 } else if messages_delivered == 5 {
3835 // Everything was delivered...
3836 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3839 if messages_delivered == 1 || messages_delivered == 2 {
3840 expect_payment_path_successful!(nodes[0]);
3843 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3844 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3845 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3847 if messages_delivered > 2 {
3848 expect_payment_path_successful!(nodes[0]);
3851 // Channel should still work fine...
3852 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3853 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3854 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3858 fn test_drop_messages_peer_disconnect_a() {
3859 do_test_drop_messages_peer_disconnect(0, true);
3860 do_test_drop_messages_peer_disconnect(0, false);
3861 do_test_drop_messages_peer_disconnect(1, false);
3862 do_test_drop_messages_peer_disconnect(2, false);
3866 fn test_drop_messages_peer_disconnect_b() {
3867 do_test_drop_messages_peer_disconnect(3, false);
3868 do_test_drop_messages_peer_disconnect(4, false);
3869 do_test_drop_messages_peer_disconnect(5, false);
3870 do_test_drop_messages_peer_disconnect(6, false);
3874 fn test_channel_ready_without_best_block_updated() {
3875 // Previously, if we were offline when a funding transaction was locked in, and then we came
3876 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3877 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3878 // channel_ready immediately instead.
3879 let chanmon_cfgs = create_chanmon_cfgs(2);
3880 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3881 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3882 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3883 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3885 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3887 let conf_height = nodes[0].best_block_info().1 + 1;
3888 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3889 let block_txn = [funding_tx];
3890 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3891 let conf_block_header = nodes[0].get_block_header(conf_height);
3892 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3894 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3895 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3896 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3900 fn test_drop_messages_peer_disconnect_dual_htlc() {
3901 // Test that we can handle reconnecting when both sides of a channel have pending
3902 // commitment_updates when we disconnect.
3903 let chanmon_cfgs = create_chanmon_cfgs(2);
3904 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3905 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3906 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3907 create_announced_chan_between_nodes(&nodes, 0, 1);
3909 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3911 // Now try to send a second payment which will fail to send
3912 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3913 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3914 check_added_monitors!(nodes[0], 1);
3916 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3917 assert_eq!(events_1.len(), 1);
3919 MessageSendEvent::UpdateHTLCs { .. } => {},
3920 _ => panic!("Unexpected event"),
3923 nodes[1].node.claim_funds(payment_preimage_1);
3924 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3925 check_added_monitors!(nodes[1], 1);
3927 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3928 assert_eq!(events_2.len(), 1);
3930 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 } } => {
3931 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3932 assert!(update_add_htlcs.is_empty());
3933 assert_eq!(update_fulfill_htlcs.len(), 1);
3934 assert!(update_fail_htlcs.is_empty());
3935 assert!(update_fail_malformed_htlcs.is_empty());
3936 assert!(update_fee.is_none());
3938 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3939 let events_3 = nodes[0].node.get_and_clear_pending_events();
3940 assert_eq!(events_3.len(), 1);
3942 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3943 assert_eq!(*payment_preimage, payment_preimage_1);
3944 assert_eq!(*payment_hash, payment_hash_1);
3946 _ => panic!("Unexpected event"),
3949 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3950 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3951 // No commitment_signed so get_event_msg's assert(len == 1) passes
3952 check_added_monitors!(nodes[0], 1);
3954 _ => panic!("Unexpected event"),
3957 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3958 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3960 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
3961 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3962 assert_eq!(reestablish_1.len(), 1);
3963 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
3964 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3965 assert_eq!(reestablish_2.len(), 1);
3967 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3968 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3969 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3970 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3972 assert!(as_resp.0.is_none());
3973 assert!(bs_resp.0.is_none());
3975 assert!(bs_resp.1.is_none());
3976 assert!(bs_resp.2.is_none());
3978 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3980 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3981 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3982 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3983 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3984 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3985 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3986 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3987 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3988 // No commitment_signed so get_event_msg's assert(len == 1) passes
3989 check_added_monitors!(nodes[1], 1);
3991 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3992 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3993 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3994 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3995 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3996 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3997 assert!(bs_second_commitment_signed.update_fee.is_none());
3998 check_added_monitors!(nodes[1], 1);
4000 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4001 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4002 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4003 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4004 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4005 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4006 assert!(as_commitment_signed.update_fee.is_none());
4007 check_added_monitors!(nodes[0], 1);
4009 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4010 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4011 // No commitment_signed so get_event_msg's assert(len == 1) passes
4012 check_added_monitors!(nodes[0], 1);
4014 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4015 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4016 // No commitment_signed so get_event_msg's assert(len == 1) passes
4017 check_added_monitors!(nodes[1], 1);
4019 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4020 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4021 check_added_monitors!(nodes[1], 1);
4023 expect_pending_htlcs_forwardable!(nodes[1]);
4025 let events_5 = nodes[1].node.get_and_clear_pending_events();
4026 assert_eq!(events_5.len(), 1);
4028 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4029 assert_eq!(payment_hash_2, *payment_hash);
4031 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4032 assert!(payment_preimage.is_none());
4033 assert_eq!(payment_secret_2, *payment_secret);
4035 _ => panic!("expected PaymentPurpose::InvoicePayment")
4038 _ => panic!("Unexpected event"),
4041 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4042 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4043 check_added_monitors!(nodes[0], 1);
4045 expect_payment_path_successful!(nodes[0]);
4046 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4049 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4050 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4051 // to avoid our counterparty failing the channel.
4052 let chanmon_cfgs = create_chanmon_cfgs(2);
4053 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4054 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4055 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4057 create_announced_chan_between_nodes(&nodes, 0, 1);
4059 let our_payment_hash = if send_partial_mpp {
4060 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4061 // Use the utility function send_payment_along_path to send the payment with MPP data which
4062 // indicates there are more HTLCs coming.
4063 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.
4064 let payment_id = PaymentId([42; 32]);
4065 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4066 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();
4067 check_added_monitors!(nodes[0], 1);
4068 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4069 assert_eq!(events.len(), 1);
4070 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4071 // hop should *not* yet generate any PaymentClaimable event(s).
4072 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4075 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4078 let mut block = Block {
4079 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4082 connect_block(&nodes[0], &block);
4083 connect_block(&nodes[1], &block);
4084 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4085 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4086 block.header.prev_blockhash = block.block_hash();
4087 connect_block(&nodes[0], &block);
4088 connect_block(&nodes[1], &block);
4091 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4093 check_added_monitors!(nodes[1], 1);
4094 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4095 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4096 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4097 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4098 assert!(htlc_timeout_updates.update_fee.is_none());
4100 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4101 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4102 // 100_000 msat as u64, followed by the height at which we failed back above
4103 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4104 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4105 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4109 fn test_htlc_timeout() {
4110 do_test_htlc_timeout(true);
4111 do_test_htlc_timeout(false);
4114 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4115 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4116 let chanmon_cfgs = create_chanmon_cfgs(3);
4117 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4118 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4119 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4120 create_announced_chan_between_nodes(&nodes, 0, 1);
4121 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4123 // Make sure all nodes are at the same starting height
4124 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4125 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4126 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4128 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4129 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4131 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4133 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4134 check_added_monitors!(nodes[1], 1);
4136 // Now attempt to route a second payment, which should be placed in the holding cell
4137 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4138 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4139 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4141 check_added_monitors!(nodes[0], 1);
4142 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4143 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4144 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4145 expect_pending_htlcs_forwardable!(nodes[1]);
4147 check_added_monitors!(nodes[1], 0);
4149 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4150 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4151 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4152 connect_blocks(&nodes[1], 1);
4155 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 }]);
4156 check_added_monitors!(nodes[1], 1);
4157 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4158 assert_eq!(fail_commit.len(), 1);
4159 match fail_commit[0] {
4160 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4161 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4162 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4164 _ => unreachable!(),
4166 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4168 expect_payment_failed!(nodes[1], second_payment_hash, false);
4173 fn test_holding_cell_htlc_add_timeouts() {
4174 do_test_holding_cell_htlc_add_timeouts(false);
4175 do_test_holding_cell_htlc_add_timeouts(true);
4178 macro_rules! check_spendable_outputs {
4179 ($node: expr, $keysinterface: expr) => {
4181 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4182 let mut txn = Vec::new();
4183 let mut all_outputs = Vec::new();
4184 let secp_ctx = Secp256k1::new();
4185 for event in events.drain(..) {
4187 Event::SpendableOutputs { mut outputs } => {
4188 for outp in outputs.drain(..) {
4189 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4190 all_outputs.push(outp);
4193 _ => panic!("Unexpected event"),
4196 if all_outputs.len() > 1 {
4197 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) {
4207 fn test_claim_sizeable_push_msat() {
4208 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4209 let chanmon_cfgs = create_chanmon_cfgs(2);
4210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4212 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4214 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4215 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4216 check_closed_broadcast!(nodes[1], true);
4217 check_added_monitors!(nodes[1], 1);
4218 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4219 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4220 assert_eq!(node_txn.len(), 1);
4221 check_spends!(node_txn[0], chan.3);
4222 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
4224 mine_transaction(&nodes[1], &node_txn[0]);
4225 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4227 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4228 assert_eq!(spend_txn.len(), 1);
4229 assert_eq!(spend_txn[0].input.len(), 1);
4230 check_spends!(spend_txn[0], node_txn[0]);
4231 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4235 fn test_claim_on_remote_sizeable_push_msat() {
4236 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4237 // to_remote output is encumbered by a P2WPKH
4238 let chanmon_cfgs = create_chanmon_cfgs(2);
4239 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4240 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4241 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4243 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4244 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4245 check_closed_broadcast!(nodes[0], true);
4246 check_added_monitors!(nodes[0], 1);
4247 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4249 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4250 assert_eq!(node_txn.len(), 1);
4251 check_spends!(node_txn[0], chan.3);
4252 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
4254 mine_transaction(&nodes[1], &node_txn[0]);
4255 check_closed_broadcast!(nodes[1], true);
4256 check_added_monitors!(nodes[1], 1);
4257 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4258 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4260 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4261 assert_eq!(spend_txn.len(), 1);
4262 check_spends!(spend_txn[0], node_txn[0]);
4266 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4267 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4268 // to_remote output is encumbered by a P2WPKH
4270 let chanmon_cfgs = create_chanmon_cfgs(2);
4271 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4272 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4273 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4275 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4276 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4277 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4278 assert_eq!(revoked_local_txn[0].input.len(), 1);
4279 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4281 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4282 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4283 check_closed_broadcast!(nodes[1], true);
4284 check_added_monitors!(nodes[1], 1);
4285 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4287 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4288 mine_transaction(&nodes[1], &node_txn[0]);
4289 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4291 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4292 assert_eq!(spend_txn.len(), 3);
4293 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4294 check_spends!(spend_txn[1], node_txn[0]);
4295 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4299 fn test_static_spendable_outputs_preimage_tx() {
4300 let chanmon_cfgs = create_chanmon_cfgs(2);
4301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4303 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4305 // Create some initial channels
4306 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4308 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4310 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4311 assert_eq!(commitment_tx[0].input.len(), 1);
4312 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4314 // Settle A's commitment tx on B's chain
4315 nodes[1].node.claim_funds(payment_preimage);
4316 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4317 check_added_monitors!(nodes[1], 1);
4318 mine_transaction(&nodes[1], &commitment_tx[0]);
4319 check_added_monitors!(nodes[1], 1);
4320 let events = nodes[1].node.get_and_clear_pending_msg_events();
4322 MessageSendEvent::UpdateHTLCs { .. } => {},
4323 _ => panic!("Unexpected event"),
4326 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4327 _ => panic!("Unexepected event"),
4330 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4331 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4332 assert_eq!(node_txn.len(), 1);
4333 check_spends!(node_txn[0], commitment_tx[0]);
4334 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4336 mine_transaction(&nodes[1], &node_txn[0]);
4337 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4338 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4340 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4341 assert_eq!(spend_txn.len(), 1);
4342 check_spends!(spend_txn[0], node_txn[0]);
4346 fn test_static_spendable_outputs_timeout_tx() {
4347 let chanmon_cfgs = create_chanmon_cfgs(2);
4348 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4349 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4350 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4352 // Create some initial channels
4353 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4355 // Rebalance the network a bit by relaying one payment through all the channels ...
4356 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4358 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4360 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4361 assert_eq!(commitment_tx[0].input.len(), 1);
4362 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4364 // Settle A's commitment tx on B' chain
4365 mine_transaction(&nodes[1], &commitment_tx[0]);
4366 check_added_monitors!(nodes[1], 1);
4367 let events = nodes[1].node.get_and_clear_pending_msg_events();
4369 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4370 _ => panic!("Unexpected event"),
4372 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4374 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4375 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4376 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4377 check_spends!(node_txn[0], commitment_tx[0].clone());
4378 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4380 mine_transaction(&nodes[1], &node_txn[0]);
4381 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4382 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4383 expect_payment_failed!(nodes[1], our_payment_hash, false);
4385 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4386 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4387 check_spends!(spend_txn[0], commitment_tx[0]);
4388 check_spends!(spend_txn[1], node_txn[0]);
4389 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4393 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4394 let chanmon_cfgs = create_chanmon_cfgs(2);
4395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4399 // Create some initial channels
4400 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4402 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4403 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4404 assert_eq!(revoked_local_txn[0].input.len(), 1);
4405 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4407 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4409 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4410 check_closed_broadcast!(nodes[1], true);
4411 check_added_monitors!(nodes[1], 1);
4412 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4414 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4415 assert_eq!(node_txn.len(), 1);
4416 assert_eq!(node_txn[0].input.len(), 2);
4417 check_spends!(node_txn[0], revoked_local_txn[0]);
4419 mine_transaction(&nodes[1], &node_txn[0]);
4420 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4422 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4423 assert_eq!(spend_txn.len(), 1);
4424 check_spends!(spend_txn[0], node_txn[0]);
4428 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4429 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4430 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4433 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4435 // Create some initial channels
4436 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4438 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4439 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4440 assert_eq!(revoked_local_txn[0].input.len(), 1);
4441 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4443 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4445 // A will generate HTLC-Timeout from revoked commitment tx
4446 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4447 check_closed_broadcast!(nodes[0], true);
4448 check_added_monitors!(nodes[0], 1);
4449 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4450 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4452 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4453 assert_eq!(revoked_htlc_txn.len(), 1);
4454 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4455 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4456 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4457 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4459 // B will generate justice tx from A's revoked commitment/HTLC tx
4460 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4461 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4462 check_closed_broadcast!(nodes[1], true);
4463 check_added_monitors!(nodes[1], 1);
4464 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4466 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4467 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4468 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4469 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4470 // transactions next...
4471 assert_eq!(node_txn[0].input.len(), 3);
4472 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4474 assert_eq!(node_txn[1].input.len(), 2);
4475 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4476 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4477 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4479 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4480 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
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);
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(), 1);
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(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
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 mine_transaction(&nodes[0], &node_txn[1]);
4556 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4558 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4559 // didn't try to generate any new transactions.
4561 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4562 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4563 assert_eq!(spend_txn.len(), 3);
4564 assert_eq!(spend_txn[0].input.len(), 1);
4565 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4566 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4567 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4568 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4572 fn test_onchain_to_onchain_claim() {
4573 // Test that in case of channel closure, we detect the state of output and claim HTLC
4574 // on downstream peer's remote commitment tx.
4575 // First, have C claim an HTLC against its own latest commitment transaction.
4576 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4578 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4581 let chanmon_cfgs = create_chanmon_cfgs(3);
4582 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4583 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4584 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4586 // Create some initial channels
4587 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4588 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4590 // Ensure all nodes are at the same height
4591 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4592 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4593 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4594 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4596 // Rebalance the network a bit by relaying one payment through all the channels ...
4597 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4598 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4600 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4601 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4602 check_spends!(commitment_tx[0], chan_2.3);
4603 nodes[2].node.claim_funds(payment_preimage);
4604 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4605 check_added_monitors!(nodes[2], 1);
4606 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4607 assert!(updates.update_add_htlcs.is_empty());
4608 assert!(updates.update_fail_htlcs.is_empty());
4609 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4610 assert!(updates.update_fail_malformed_htlcs.is_empty());
4612 mine_transaction(&nodes[2], &commitment_tx[0]);
4613 check_closed_broadcast!(nodes[2], true);
4614 check_added_monitors!(nodes[2], 1);
4615 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4617 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4618 assert_eq!(c_txn.len(), 1);
4619 check_spends!(c_txn[0], commitment_tx[0]);
4620 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4621 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4622 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4624 // 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
4625 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4626 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4627 check_added_monitors!(nodes[1], 1);
4628 let events = nodes[1].node.get_and_clear_pending_events();
4629 assert_eq!(events.len(), 2);
4631 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4632 _ => panic!("Unexpected event"),
4635 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4636 assert_eq!(fee_earned_msat, Some(1000));
4637 assert_eq!(prev_channel_id, Some(chan_1.2));
4638 assert_eq!(claim_from_onchain_tx, true);
4639 assert_eq!(next_channel_id, Some(chan_2.2));
4641 _ => panic!("Unexpected event"),
4643 check_added_monitors!(nodes[1], 1);
4644 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4645 assert_eq!(msg_events.len(), 3);
4646 let (nodes_2_event, msg_events) = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &msg_events);
4647 let (nodes_0_event, msg_events) = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &msg_events);
4649 match nodes_2_event {
4650 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4651 _ => panic!("Unexpected event"),
4654 match nodes_0_event {
4655 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, .. } } => {
4656 assert!(update_add_htlcs.is_empty());
4657 assert!(update_fail_htlcs.is_empty());
4658 assert_eq!(update_fulfill_htlcs.len(), 1);
4659 assert!(update_fail_malformed_htlcs.is_empty());
4660 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4662 _ => panic!("Unexpected event"),
4665 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4666 match msg_events[0] {
4667 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4668 _ => panic!("Unexpected event"),
4671 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4672 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4673 mine_transaction(&nodes[1], &commitment_tx[0]);
4674 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4675 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4676 // ChannelMonitor: HTLC-Success tx
4677 assert_eq!(b_txn.len(), 1);
4678 check_spends!(b_txn[0], commitment_tx[0]);
4679 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4680 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4681 assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
4683 check_closed_broadcast!(nodes[1], true);
4684 check_added_monitors!(nodes[1], 1);
4688 fn test_duplicate_payment_hash_one_failure_one_success() {
4689 // Topology : A --> B --> C --> D
4690 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4691 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4692 // we forward one of the payments onwards to D.
4693 let chanmon_cfgs = create_chanmon_cfgs(4);
4694 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4695 // When this test was written, the default base fee floated based on the HTLC count.
4696 // It is now fixed, so we simply set the fee to the expected value here.
4697 let mut config = test_default_channel_config();
4698 config.channel_config.forwarding_fee_base_msat = 196;
4699 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4700 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4701 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4703 create_announced_chan_between_nodes(&nodes, 0, 1);
4704 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4705 create_announced_chan_between_nodes(&nodes, 2, 3);
4707 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4708 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4709 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4710 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4711 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4713 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4715 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4716 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4717 // script push size limit so that the below script length checks match
4718 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4719 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
4720 .with_features(nodes[3].node.invoice_features());
4721 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4722 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4724 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4725 assert_eq!(commitment_txn[0].input.len(), 1);
4726 check_spends!(commitment_txn[0], chan_2.3);
4728 mine_transaction(&nodes[1], &commitment_txn[0]);
4729 check_closed_broadcast!(nodes[1], true);
4730 check_added_monitors!(nodes[1], 1);
4731 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4732 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4734 let htlc_timeout_tx;
4735 { // Extract one of the two HTLC-Timeout transaction
4736 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4737 // ChannelMonitor: timeout tx * 2-or-3
4738 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4740 check_spends!(node_txn[0], commitment_txn[0]);
4741 assert_eq!(node_txn[0].input.len(), 1);
4742 assert_eq!(node_txn[0].output.len(), 1);
4744 if node_txn.len() > 2 {
4745 check_spends!(node_txn[1], commitment_txn[0]);
4746 assert_eq!(node_txn[1].input.len(), 1);
4747 assert_eq!(node_txn[1].output.len(), 1);
4748 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4750 check_spends!(node_txn[2], commitment_txn[0]);
4751 assert_eq!(node_txn[2].input.len(), 1);
4752 assert_eq!(node_txn[2].output.len(), 1);
4753 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4755 check_spends!(node_txn[1], commitment_txn[0]);
4756 assert_eq!(node_txn[1].input.len(), 1);
4757 assert_eq!(node_txn[1].output.len(), 1);
4758 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4761 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4762 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4763 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4764 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4765 if node_txn.len() > 2 {
4766 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4767 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4769 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4773 nodes[2].node.claim_funds(our_payment_preimage);
4774 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4776 mine_transaction(&nodes[2], &commitment_txn[0]);
4777 check_added_monitors!(nodes[2], 2);
4778 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4779 let events = nodes[2].node.get_and_clear_pending_msg_events();
4781 MessageSendEvent::UpdateHTLCs { .. } => {},
4782 _ => panic!("Unexpected event"),
4785 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4786 _ => panic!("Unexepected event"),
4788 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4789 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4790 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4791 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4792 assert_eq!(htlc_success_txn[0].input.len(), 1);
4793 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4794 assert_eq!(htlc_success_txn[1].input.len(), 1);
4795 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4796 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4797 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4799 mine_transaction(&nodes[1], &htlc_timeout_tx);
4800 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4801 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 }]);
4802 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4803 assert!(htlc_updates.update_add_htlcs.is_empty());
4804 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4805 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4806 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4807 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4808 check_added_monitors!(nodes[1], 1);
4810 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4811 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4813 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4815 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4817 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4818 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
4819 // and nodes[2] fee) is rounded down and then claimed in full.
4820 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4821 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4822 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4823 assert!(updates.update_add_htlcs.is_empty());
4824 assert!(updates.update_fail_htlcs.is_empty());
4825 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4826 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4827 assert!(updates.update_fail_malformed_htlcs.is_empty());
4828 check_added_monitors!(nodes[1], 1);
4830 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4831 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4833 let events = nodes[0].node.get_and_clear_pending_events();
4835 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4836 assert_eq!(*payment_preimage, our_payment_preimage);
4837 assert_eq!(*payment_hash, duplicate_payment_hash);
4839 _ => panic!("Unexpected event"),
4844 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4845 let chanmon_cfgs = create_chanmon_cfgs(2);
4846 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4847 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4848 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4850 // Create some initial channels
4851 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4853 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4854 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4855 assert_eq!(local_txn.len(), 1);
4856 assert_eq!(local_txn[0].input.len(), 1);
4857 check_spends!(local_txn[0], chan_1.3);
4859 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4860 nodes[1].node.claim_funds(payment_preimage);
4861 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4862 check_added_monitors!(nodes[1], 1);
4864 mine_transaction(&nodes[1], &local_txn[0]);
4865 check_added_monitors!(nodes[1], 1);
4866 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4867 let events = nodes[1].node.get_and_clear_pending_msg_events();
4869 MessageSendEvent::UpdateHTLCs { .. } => {},
4870 _ => panic!("Unexpected event"),
4873 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4874 _ => panic!("Unexepected event"),
4877 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4878 assert_eq!(node_txn.len(), 1);
4879 assert_eq!(node_txn[0].input.len(), 1);
4880 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4881 check_spends!(node_txn[0], local_txn[0]);
4885 mine_transaction(&nodes[1], &node_tx);
4886 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4888 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4889 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4890 assert_eq!(spend_txn.len(), 1);
4891 assert_eq!(spend_txn[0].input.len(), 1);
4892 check_spends!(spend_txn[0], node_tx);
4893 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4896 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4897 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4898 // unrevoked commitment transaction.
4899 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4900 // a remote RAA before they could be failed backwards (and combinations thereof).
4901 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4902 // use the same payment hashes.
4903 // Thus, we use a six-node network:
4908 // And test where C fails back to A/B when D announces its latest commitment transaction
4909 let chanmon_cfgs = create_chanmon_cfgs(6);
4910 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4911 // When this test was written, the default base fee floated based on the HTLC count.
4912 // It is now fixed, so we simply set the fee to the expected value here.
4913 let mut config = test_default_channel_config();
4914 config.channel_config.forwarding_fee_base_msat = 196;
4915 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4916 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4917 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4919 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4920 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4921 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4922 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4923 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4925 // Rebalance and check output sanity...
4926 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4927 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4928 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4930 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4931 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4933 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
4935 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
4936 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4938 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4940 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4942 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4944 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4945 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4947 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, None).unwrap());
4949 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, None).unwrap());
4952 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4954 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4955 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4958 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
4960 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4961 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, None).unwrap());
4963 // Double-check that six of the new HTLC were added
4964 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4965 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4966 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4967 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4969 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4970 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4971 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4972 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4973 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4974 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4975 check_added_monitors!(nodes[4], 0);
4977 let failed_destinations = vec![
4978 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4979 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4980 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
4981 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
4983 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
4984 check_added_monitors!(nodes[4], 1);
4986 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4987 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4988 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4989 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4990 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4991 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4993 // Fail 3rd below-dust and 7th above-dust HTLCs
4994 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
4995 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
4996 check_added_monitors!(nodes[5], 0);
4998 let failed_destinations_2 = vec![
4999 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5000 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5002 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5003 check_added_monitors!(nodes[5], 1);
5005 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5006 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5007 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5008 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5010 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5012 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5013 let failed_destinations_3 = vec![
5014 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5015 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5016 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
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[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5019 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5021 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5022 check_added_monitors!(nodes[3], 1);
5023 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5024 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5025 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5026 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5027 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5028 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5029 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5030 if deliver_last_raa {
5031 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5033 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5036 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5037 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5038 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5039 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5041 // We now broadcast the latest commitment transaction, which *should* result in failures for
5042 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5043 // the non-broadcast above-dust HTLCs.
5045 // Alternatively, we may broadcast the previous commitment transaction, which should only
5046 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5047 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5049 if announce_latest {
5050 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5052 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5054 let events = nodes[2].node.get_and_clear_pending_events();
5055 let close_event = if deliver_last_raa {
5056 assert_eq!(events.len(), 2 + 6);
5057 events.last().clone().unwrap()
5059 assert_eq!(events.len(), 1);
5060 events.last().clone().unwrap()
5063 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5064 _ => panic!("Unexpected event"),
5067 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5068 check_closed_broadcast!(nodes[2], true);
5069 if deliver_last_raa {
5070 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5072 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();
5073 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5075 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5076 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5078 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5081 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5083 check_added_monitors!(nodes[2], 3);
5085 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5086 assert_eq!(cs_msgs.len(), 2);
5087 let mut a_done = false;
5088 for msg in cs_msgs {
5090 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5091 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5092 // should be failed-backwards here.
5093 let target = if *node_id == nodes[0].node.get_our_node_id() {
5094 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5095 for htlc in &updates.update_fail_htlcs {
5096 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 });
5098 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5103 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5104 for htlc in &updates.update_fail_htlcs {
5105 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5107 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5108 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5111 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5112 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5113 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5114 if announce_latest {
5115 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5116 if *node_id == nodes[0].node.get_our_node_id() {
5117 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5120 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5122 _ => panic!("Unexpected event"),
5126 let as_events = nodes[0].node.get_and_clear_pending_events();
5127 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5128 let mut as_failds = HashSet::new();
5129 let mut as_updates = 0;
5130 for event in as_events.iter() {
5131 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5132 assert!(as_failds.insert(*payment_hash));
5133 if *payment_hash != payment_hash_2 {
5134 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5136 assert!(!payment_failed_permanently);
5138 if network_update.is_some() {
5141 } else { panic!("Unexpected event"); }
5143 assert!(as_failds.contains(&payment_hash_1));
5144 assert!(as_failds.contains(&payment_hash_2));
5145 if announce_latest {
5146 assert!(as_failds.contains(&payment_hash_3));
5147 assert!(as_failds.contains(&payment_hash_5));
5149 assert!(as_failds.contains(&payment_hash_6));
5151 let bs_events = nodes[1].node.get_and_clear_pending_events();
5152 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5153 let mut bs_failds = HashSet::new();
5154 let mut bs_updates = 0;
5155 for event in bs_events.iter() {
5156 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5157 assert!(bs_failds.insert(*payment_hash));
5158 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5159 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5161 assert!(!payment_failed_permanently);
5163 if network_update.is_some() {
5166 } else { panic!("Unexpected event"); }
5168 assert!(bs_failds.contains(&payment_hash_1));
5169 assert!(bs_failds.contains(&payment_hash_2));
5170 if announce_latest {
5171 assert!(bs_failds.contains(&payment_hash_4));
5173 assert!(bs_failds.contains(&payment_hash_5));
5175 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5176 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5177 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5178 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5179 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5180 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5184 fn test_fail_backwards_latest_remote_announce_a() {
5185 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5189 fn test_fail_backwards_latest_remote_announce_b() {
5190 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5194 fn test_fail_backwards_previous_remote_announce() {
5195 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5196 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5197 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5201 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5202 let chanmon_cfgs = create_chanmon_cfgs(2);
5203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5205 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5207 // Create some initial channels
5208 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5210 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5211 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5212 assert_eq!(local_txn[0].input.len(), 1);
5213 check_spends!(local_txn[0], chan_1.3);
5215 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5216 mine_transaction(&nodes[0], &local_txn[0]);
5217 check_closed_broadcast!(nodes[0], true);
5218 check_added_monitors!(nodes[0], 1);
5219 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5220 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5222 let htlc_timeout = {
5223 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5224 assert_eq!(node_txn.len(), 1);
5225 assert_eq!(node_txn[0].input.len(), 1);
5226 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5227 check_spends!(node_txn[0], local_txn[0]);
5231 mine_transaction(&nodes[0], &htlc_timeout);
5232 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5233 expect_payment_failed!(nodes[0], our_payment_hash, false);
5235 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5236 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5237 assert_eq!(spend_txn.len(), 3);
5238 check_spends!(spend_txn[0], local_txn[0]);
5239 assert_eq!(spend_txn[1].input.len(), 1);
5240 check_spends!(spend_txn[1], htlc_timeout);
5241 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5242 assert_eq!(spend_txn[2].input.len(), 2);
5243 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5244 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5245 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5249 fn test_key_derivation_params() {
5250 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5251 // manager rotation to test that `channel_keys_id` returned in
5252 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5253 // then derive a `delayed_payment_key`.
5255 let chanmon_cfgs = create_chanmon_cfgs(3);
5257 // We manually create the node configuration to backup the seed.
5258 let seed = [42; 32];
5259 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5260 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);
5261 let network_graph = Arc::new(NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger));
5262 let router = test_utils::TestRouter::new(network_graph.clone());
5263 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5264 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5265 node_cfgs.remove(0);
5266 node_cfgs.insert(0, node);
5268 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5269 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5271 // Create some initial channels
5272 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5274 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5275 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5276 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5278 // Ensure all nodes are at the same height
5279 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5280 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5281 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5282 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5284 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5285 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5286 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5287 assert_eq!(local_txn_1[0].input.len(), 1);
5288 check_spends!(local_txn_1[0], chan_1.3);
5290 // We check funding pubkey are unique
5291 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]));
5292 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]));
5293 if from_0_funding_key_0 == from_1_funding_key_0
5294 || from_0_funding_key_0 == from_1_funding_key_1
5295 || from_0_funding_key_1 == from_1_funding_key_0
5296 || from_0_funding_key_1 == from_1_funding_key_1 {
5297 panic!("Funding pubkeys aren't unique");
5300 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5301 mine_transaction(&nodes[0], &local_txn_1[0]);
5302 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5303 check_closed_broadcast!(nodes[0], true);
5304 check_added_monitors!(nodes[0], 1);
5305 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5307 let htlc_timeout = {
5308 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5309 assert_eq!(node_txn.len(), 1);
5310 assert_eq!(node_txn[0].input.len(), 1);
5311 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5312 check_spends!(node_txn[0], local_txn_1[0]);
5316 mine_transaction(&nodes[0], &htlc_timeout);
5317 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5318 expect_payment_failed!(nodes[0], our_payment_hash, false);
5320 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5321 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5322 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5323 assert_eq!(spend_txn.len(), 3);
5324 check_spends!(spend_txn[0], local_txn_1[0]);
5325 assert_eq!(spend_txn[1].input.len(), 1);
5326 check_spends!(spend_txn[1], htlc_timeout);
5327 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5328 assert_eq!(spend_txn[2].input.len(), 2);
5329 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5330 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5331 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5335 fn test_static_output_closing_tx() {
5336 let chanmon_cfgs = create_chanmon_cfgs(2);
5337 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5338 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5339 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5341 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5343 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5344 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5346 mine_transaction(&nodes[0], &closing_tx);
5347 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5348 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5350 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5351 assert_eq!(spend_txn.len(), 1);
5352 check_spends!(spend_txn[0], closing_tx);
5354 mine_transaction(&nodes[1], &closing_tx);
5355 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5356 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5358 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5359 assert_eq!(spend_txn.len(), 1);
5360 check_spends!(spend_txn[0], closing_tx);
5363 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5364 let chanmon_cfgs = create_chanmon_cfgs(2);
5365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5367 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5368 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5370 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5372 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5373 // present in B's local commitment transaction, but none of A's commitment transactions.
5374 nodes[1].node.claim_funds(payment_preimage);
5375 check_added_monitors!(nodes[1], 1);
5376 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5378 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5379 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5380 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5382 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5383 check_added_monitors!(nodes[0], 1);
5384 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5385 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5386 check_added_monitors!(nodes[1], 1);
5388 let starting_block = nodes[1].best_block_info();
5389 let mut block = Block {
5390 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5393 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5394 connect_block(&nodes[1], &block);
5395 block.header.prev_blockhash = block.block_hash();
5397 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5398 check_closed_broadcast!(nodes[1], true);
5399 check_added_monitors!(nodes[1], 1);
5400 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5403 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5404 let chanmon_cfgs = create_chanmon_cfgs(2);
5405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5407 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5408 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5410 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5411 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5412 check_added_monitors!(nodes[0], 1);
5414 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5416 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5417 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5418 // to "time out" the HTLC.
5420 let starting_block = nodes[1].best_block_info();
5421 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5423 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5424 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5425 header.prev_blockhash = header.block_hash();
5427 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5428 check_closed_broadcast!(nodes[0], true);
5429 check_added_monitors!(nodes[0], 1);
5430 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5433 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5434 let chanmon_cfgs = create_chanmon_cfgs(3);
5435 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5436 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5437 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5438 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5440 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5441 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5442 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5443 // actually revoked.
5444 let htlc_value = if use_dust { 50000 } else { 3000000 };
5445 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5446 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5447 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5448 check_added_monitors!(nodes[1], 1);
5450 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5451 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5452 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5453 check_added_monitors!(nodes[0], 1);
5454 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5455 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5456 check_added_monitors!(nodes[1], 1);
5457 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5458 check_added_monitors!(nodes[1], 1);
5459 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5461 if check_revoke_no_close {
5462 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5463 check_added_monitors!(nodes[0], 1);
5466 let starting_block = nodes[1].best_block_info();
5467 let mut block = Block {
5468 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5471 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5472 connect_block(&nodes[0], &block);
5473 block.header.prev_blockhash = block.block_hash();
5475 if !check_revoke_no_close {
5476 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5477 check_closed_broadcast!(nodes[0], true);
5478 check_added_monitors!(nodes[0], 1);
5479 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5481 expect_payment_failed!(nodes[0], our_payment_hash, true);
5485 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5486 // There are only a few cases to test here:
5487 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5488 // broadcastable commitment transactions result in channel closure,
5489 // * its included in an unrevoked-but-previous remote commitment transaction,
5490 // * its included in the latest remote or local commitment transactions.
5491 // We test each of the three possible commitment transactions individually and use both dust and
5493 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5494 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5495 // tested for at least one of the cases in other tests.
5497 fn htlc_claim_single_commitment_only_a() {
5498 do_htlc_claim_local_commitment_only(true);
5499 do_htlc_claim_local_commitment_only(false);
5501 do_htlc_claim_current_remote_commitment_only(true);
5502 do_htlc_claim_current_remote_commitment_only(false);
5506 fn htlc_claim_single_commitment_only_b() {
5507 do_htlc_claim_previous_remote_commitment_only(true, false);
5508 do_htlc_claim_previous_remote_commitment_only(false, false);
5509 do_htlc_claim_previous_remote_commitment_only(true, true);
5510 do_htlc_claim_previous_remote_commitment_only(false, true);
5515 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5516 let chanmon_cfgs = create_chanmon_cfgs(2);
5517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5519 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5520 // Force duplicate randomness for every get-random call
5521 for node in nodes.iter() {
5522 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5525 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5526 let channel_value_satoshis=10000;
5527 let push_msat=10001;
5528 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5529 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5530 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5531 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5533 // Create a second channel with the same random values. This used to panic due to a colliding
5534 // channel_id, but now panics due to a colliding outbound SCID alias.
5535 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5539 fn bolt2_open_channel_sending_node_checks_part2() {
5540 let chanmon_cfgs = create_chanmon_cfgs(2);
5541 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5542 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5543 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5545 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5546 let channel_value_satoshis=2^24;
5547 let push_msat=10001;
5548 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5550 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5551 let channel_value_satoshis=10000;
5552 // Test when push_msat is equal to 1000 * funding_satoshis.
5553 let push_msat=1000*channel_value_satoshis+1;
5554 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5556 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5557 let channel_value_satoshis=10000;
5558 let push_msat=10001;
5559 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
5560 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5561 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5563 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5564 // 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
5565 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5567 // 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.
5568 assert!(BREAKDOWN_TIMEOUT>0);
5569 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5571 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5572 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5573 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5575 // 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.
5576 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5577 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5578 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5579 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5580 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5584 fn bolt2_open_channel_sane_dust_limit() {
5585 let chanmon_cfgs = create_chanmon_cfgs(2);
5586 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5587 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5588 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5590 let channel_value_satoshis=1000000;
5591 let push_msat=10001;
5592 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5593 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5594 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5595 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5597 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5598 let events = nodes[1].node.get_and_clear_pending_msg_events();
5599 let err_msg = match events[0] {
5600 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5603 _ => panic!("Unexpected event"),
5605 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5608 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5609 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5610 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5611 // is no longer affordable once it's freed.
5613 fn test_fail_holding_cell_htlc_upon_free() {
5614 let chanmon_cfgs = create_chanmon_cfgs(2);
5615 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5616 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5617 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5618 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5620 // First nodes[0] generates an update_fee, setting the channel's
5621 // pending_update_fee.
5623 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5624 *feerate_lock += 20;
5626 nodes[0].node.timer_tick_occurred();
5627 check_added_monitors!(nodes[0], 1);
5629 let events = nodes[0].node.get_and_clear_pending_msg_events();
5630 assert_eq!(events.len(), 1);
5631 let (update_msg, commitment_signed) = match events[0] {
5632 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5633 (update_fee.as_ref(), commitment_signed)
5635 _ => panic!("Unexpected event"),
5638 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5640 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5641 let channel_reserve = chan_stat.channel_reserve_msat;
5642 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5643 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5645 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5646 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5647 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5649 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5650 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5651 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5652 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5654 // Flush the pending fee update.
5655 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5656 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5657 check_added_monitors!(nodes[1], 1);
5658 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5659 check_added_monitors!(nodes[0], 1);
5661 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5662 // HTLC, but now that the fee has been raised the payment will now fail, causing
5663 // us to surface its failure to the user.
5664 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5665 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5666 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);
5667 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 {}",
5668 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5669 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5671 // Check that the payment failed to be sent out.
5672 let events = nodes[0].node.get_and_clear_pending_events();
5673 assert_eq!(events.len(), 1);
5675 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5676 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5677 assert_eq!(our_payment_hash.clone(), *payment_hash);
5678 assert_eq!(*payment_failed_permanently, false);
5679 assert_eq!(*all_paths_failed, true);
5680 assert_eq!(*network_update, None);
5681 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5683 _ => panic!("Unexpected event"),
5687 // Test that if multiple HTLCs are released from the holding cell and one is
5688 // valid but the other is no longer valid upon release, the valid HTLC can be
5689 // successfully completed while the other one fails as expected.
5691 fn test_free_and_fail_holding_cell_htlcs() {
5692 let chanmon_cfgs = create_chanmon_cfgs(2);
5693 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5694 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5695 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5696 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5698 // First nodes[0] generates an update_fee, setting the channel's
5699 // pending_update_fee.
5701 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5702 *feerate_lock += 200;
5704 nodes[0].node.timer_tick_occurred();
5705 check_added_monitors!(nodes[0], 1);
5707 let events = nodes[0].node.get_and_clear_pending_msg_events();
5708 assert_eq!(events.len(), 1);
5709 let (update_msg, commitment_signed) = match events[0] {
5710 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5711 (update_fee.as_ref(), commitment_signed)
5713 _ => panic!("Unexpected event"),
5716 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5718 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5719 let channel_reserve = chan_stat.channel_reserve_msat;
5720 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5721 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5723 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5725 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5726 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5727 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5729 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5730 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5731 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5732 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5733 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5734 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5735 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5736 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5738 // Flush the pending fee update.
5739 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5740 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5741 check_added_monitors!(nodes[1], 1);
5742 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5743 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5744 check_added_monitors!(nodes[0], 2);
5746 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5747 // but now that the fee has been raised the second payment will now fail, causing us
5748 // to surface its failure to the user. The first payment should succeed.
5749 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5750 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5751 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);
5752 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 {}",
5753 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5754 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5756 // Check that the second payment failed to be sent out.
5757 let events = nodes[0].node.get_and_clear_pending_events();
5758 assert_eq!(events.len(), 1);
5760 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5761 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5762 assert_eq!(payment_hash_2.clone(), *payment_hash);
5763 assert_eq!(*payment_failed_permanently, false);
5764 assert_eq!(*all_paths_failed, true);
5765 assert_eq!(*network_update, None);
5766 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5768 _ => panic!("Unexpected event"),
5771 // Complete the first payment and the RAA from the fee update.
5772 let (payment_event, send_raa_event) = {
5773 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5774 assert_eq!(msgs.len(), 2);
5775 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5777 let raa = match send_raa_event {
5778 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5779 _ => panic!("Unexpected event"),
5781 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5782 check_added_monitors!(nodes[1], 1);
5783 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5784 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5785 let events = nodes[1].node.get_and_clear_pending_events();
5786 assert_eq!(events.len(), 1);
5788 Event::PendingHTLCsForwardable { .. } => {},
5789 _ => panic!("Unexpected event"),
5791 nodes[1].node.process_pending_htlc_forwards();
5792 let events = nodes[1].node.get_and_clear_pending_events();
5793 assert_eq!(events.len(), 1);
5795 Event::PaymentClaimable { .. } => {},
5796 _ => panic!("Unexpected event"),
5798 nodes[1].node.claim_funds(payment_preimage_1);
5799 check_added_monitors!(nodes[1], 1);
5800 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5802 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5803 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5804 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5805 expect_payment_sent!(nodes[0], payment_preimage_1);
5808 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5809 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5810 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5813 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5814 let chanmon_cfgs = create_chanmon_cfgs(3);
5815 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5816 // When this test was written, the default base fee floated based on the HTLC count.
5817 // It is now fixed, so we simply set the fee to the expected value here.
5818 let mut config = test_default_channel_config();
5819 config.channel_config.forwarding_fee_base_msat = 196;
5820 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5821 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5822 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5823 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5825 // First nodes[1] generates an update_fee, setting the channel's
5826 // pending_update_fee.
5828 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5829 *feerate_lock += 20;
5831 nodes[1].node.timer_tick_occurred();
5832 check_added_monitors!(nodes[1], 1);
5834 let events = nodes[1].node.get_and_clear_pending_msg_events();
5835 assert_eq!(events.len(), 1);
5836 let (update_msg, commitment_signed) = match events[0] {
5837 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5838 (update_fee.as_ref(), commitment_signed)
5840 _ => panic!("Unexpected event"),
5843 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5845 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5846 let channel_reserve = chan_stat.channel_reserve_msat;
5847 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5848 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5850 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5852 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5853 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5854 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5855 let payment_event = {
5856 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5857 check_added_monitors!(nodes[0], 1);
5859 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5860 assert_eq!(events.len(), 1);
5862 SendEvent::from_event(events.remove(0))
5864 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5865 check_added_monitors!(nodes[1], 0);
5866 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5867 expect_pending_htlcs_forwardable!(nodes[1]);
5869 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5870 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5872 // Flush the pending fee update.
5873 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5874 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5875 check_added_monitors!(nodes[2], 1);
5876 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5877 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5878 check_added_monitors!(nodes[1], 2);
5880 // A final RAA message is generated to finalize the fee update.
5881 let events = nodes[1].node.get_and_clear_pending_msg_events();
5882 assert_eq!(events.len(), 1);
5884 let raa_msg = match &events[0] {
5885 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5888 _ => panic!("Unexpected event"),
5891 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5892 check_added_monitors!(nodes[2], 1);
5893 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5895 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5896 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5897 assert_eq!(process_htlc_forwards_event.len(), 2);
5898 match &process_htlc_forwards_event[0] {
5899 &Event::PendingHTLCsForwardable { .. } => {},
5900 _ => panic!("Unexpected event"),
5903 // In response, we call ChannelManager's process_pending_htlc_forwards
5904 nodes[1].node.process_pending_htlc_forwards();
5905 check_added_monitors!(nodes[1], 1);
5907 // This causes the HTLC to be failed backwards.
5908 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5909 assert_eq!(fail_event.len(), 1);
5910 let (fail_msg, commitment_signed) = match &fail_event[0] {
5911 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5912 assert_eq!(updates.update_add_htlcs.len(), 0);
5913 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5914 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5915 assert_eq!(updates.update_fail_htlcs.len(), 1);
5916 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5918 _ => panic!("Unexpected event"),
5921 // Pass the failure messages back to nodes[0].
5922 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5923 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5925 // Complete the HTLC failure+removal process.
5926 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5927 check_added_monitors!(nodes[0], 1);
5928 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5929 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5930 check_added_monitors!(nodes[1], 2);
5931 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5932 assert_eq!(final_raa_event.len(), 1);
5933 let raa = match &final_raa_event[0] {
5934 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5935 _ => panic!("Unexpected event"),
5937 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5938 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5939 check_added_monitors!(nodes[0], 1);
5942 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5943 // 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.
5944 //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.
5947 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5948 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5949 let chanmon_cfgs = create_chanmon_cfgs(2);
5950 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5951 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5952 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5953 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5955 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5956 route.paths[0][0].fee_msat = 100;
5958 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 },
5959 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5960 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5961 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5965 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5966 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5967 let chanmon_cfgs = create_chanmon_cfgs(2);
5968 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5969 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5970 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5971 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5973 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5974 route.paths[0][0].fee_msat = 0;
5975 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 },
5976 assert_eq!(err, "Cannot send 0-msat HTLC"));
5978 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5979 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5983 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5984 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5985 let chanmon_cfgs = create_chanmon_cfgs(2);
5986 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5987 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5988 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5989 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5991 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5992 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5993 check_added_monitors!(nodes[0], 1);
5994 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5995 updates.update_add_htlcs[0].amount_msat = 0;
5997 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5998 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5999 check_closed_broadcast!(nodes[1], true).unwrap();
6000 check_added_monitors!(nodes[1], 1);
6001 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6005 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6006 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6007 //It is enforced when constructing a route.
6008 let chanmon_cfgs = create_chanmon_cfgs(2);
6009 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6010 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6011 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6012 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6014 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6015 .with_features(nodes[1].node.invoice_features());
6016 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6017 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6018 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::InvalidRoute { ref err },
6019 assert_eq!(err, &"Channel CLTV overflowed?"));
6023 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6024 //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.
6025 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6026 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6027 let chanmon_cfgs = create_chanmon_cfgs(2);
6028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6030 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6031 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6032 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6033 .unwrap().lock().unwrap().channel_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_claimable!(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);
6074 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], 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);
6100 let htlc_minimum_msat: u64;
6102 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6103 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6104 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6105 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6108 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6109 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6110 check_added_monitors!(nodes[0], 1);
6111 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6112 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6113 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6114 assert!(nodes[1].node.list_channels().is_empty());
6115 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6116 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()));
6117 check_added_monitors!(nodes[1], 1);
6118 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6122 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6123 //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
6124 let chanmon_cfgs = create_chanmon_cfgs(2);
6125 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6126 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6127 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6128 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6130 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6131 let channel_reserve = chan_stat.channel_reserve_msat;
6132 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6133 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6134 // The 2* and +1 are for the fee spike reserve.
6135 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6137 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6138 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6139 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6140 check_added_monitors!(nodes[0], 1);
6141 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6143 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6144 // at this time channel-initiatee receivers are not required to enforce that senders
6145 // respect the fee_spike_reserve.
6146 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6147 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6149 assert!(nodes[1].node.list_channels().is_empty());
6150 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6151 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6152 check_added_monitors!(nodes[1], 1);
6153 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6157 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6158 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6159 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6160 let chanmon_cfgs = create_chanmon_cfgs(2);
6161 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6162 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6163 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6164 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6166 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6167 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6168 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6169 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6170 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6171 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6173 let mut msg = msgs::UpdateAddHTLC {
6177 payment_hash: our_payment_hash,
6178 cltv_expiry: htlc_cltv,
6179 onion_routing_packet: onion_packet.clone(),
6182 for i in 0..super::channel::OUR_MAX_HTLCS {
6183 msg.htlc_id = i as u64;
6184 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6186 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6187 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6189 assert!(nodes[1].node.list_channels().is_empty());
6190 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6191 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6192 check_added_monitors!(nodes[1], 1);
6193 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6197 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6198 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6199 let chanmon_cfgs = create_chanmon_cfgs(2);
6200 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6201 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6202 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6203 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6205 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6206 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6207 check_added_monitors!(nodes[0], 1);
6208 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6209 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6210 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6212 assert!(nodes[1].node.list_channels().is_empty());
6213 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6214 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6215 check_added_monitors!(nodes[1], 1);
6216 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6220 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6221 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6222 let chanmon_cfgs = create_chanmon_cfgs(2);
6223 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6224 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6225 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6227 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6228 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6229 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6230 check_added_monitors!(nodes[0], 1);
6231 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6232 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6233 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6235 assert!(nodes[1].node.list_channels().is_empty());
6236 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6237 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6238 check_added_monitors!(nodes[1], 1);
6239 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6243 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6244 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6245 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6246 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6247 let chanmon_cfgs = create_chanmon_cfgs(2);
6248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6250 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6252 create_announced_chan_between_nodes(&nodes, 0, 1);
6253 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6254 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6255 check_added_monitors!(nodes[0], 1);
6256 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6257 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6259 //Disconnect and Reconnect
6260 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6261 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6262 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
6263 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6264 assert_eq!(reestablish_1.len(), 1);
6265 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
6266 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6267 assert_eq!(reestablish_2.len(), 1);
6268 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6269 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6270 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6271 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6274 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6275 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6276 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6277 check_added_monitors!(nodes[1], 1);
6278 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6280 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6282 assert!(nodes[1].node.list_channels().is_empty());
6283 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6284 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6285 check_added_monitors!(nodes[1], 1);
6286 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6290 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6291 //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.
6293 let chanmon_cfgs = create_chanmon_cfgs(2);
6294 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6295 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6296 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6297 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6298 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6299 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6301 check_added_monitors!(nodes[0], 1);
6302 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6303 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6305 let update_msg = msgs::UpdateFulfillHTLC{
6308 payment_preimage: our_payment_preimage,
6311 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6313 assert!(nodes[0].node.list_channels().is_empty());
6314 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6315 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()));
6316 check_added_monitors!(nodes[0], 1);
6317 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6321 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6322 //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.
6324 let chanmon_cfgs = create_chanmon_cfgs(2);
6325 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6326 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6327 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6328 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6330 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6331 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6332 check_added_monitors!(nodes[0], 1);
6333 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6334 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6336 let update_msg = msgs::UpdateFailHTLC{
6339 reason: msgs::OnionErrorPacket { data: Vec::new()},
6342 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6344 assert!(nodes[0].node.list_channels().is_empty());
6345 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6346 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()));
6347 check_added_monitors!(nodes[0], 1);
6348 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6352 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6353 //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.
6355 let chanmon_cfgs = create_chanmon_cfgs(2);
6356 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6357 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6358 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6359 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6361 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6362 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6363 check_added_monitors!(nodes[0], 1);
6364 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6365 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6366 let update_msg = msgs::UpdateFailMalformedHTLC{
6369 sha256_of_onion: [1; 32],
6370 failure_code: 0x8000,
6373 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6375 assert!(nodes[0].node.list_channels().is_empty());
6376 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6377 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()));
6378 check_added_monitors!(nodes[0], 1);
6379 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6383 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6384 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6386 let chanmon_cfgs = create_chanmon_cfgs(2);
6387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6389 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6390 create_announced_chan_between_nodes(&nodes, 0, 1);
6392 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6394 nodes[1].node.claim_funds(our_payment_preimage);
6395 check_added_monitors!(nodes[1], 1);
6396 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6398 let events = nodes[1].node.get_and_clear_pending_msg_events();
6399 assert_eq!(events.len(), 1);
6400 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6402 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, .. } } => {
6403 assert!(update_add_htlcs.is_empty());
6404 assert_eq!(update_fulfill_htlcs.len(), 1);
6405 assert!(update_fail_htlcs.is_empty());
6406 assert!(update_fail_malformed_htlcs.is_empty());
6407 assert!(update_fee.is_none());
6408 update_fulfill_htlcs[0].clone()
6410 _ => panic!("Unexpected event"),
6414 update_fulfill_msg.htlc_id = 1;
6416 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6418 assert!(nodes[0].node.list_channels().is_empty());
6419 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6420 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6421 check_added_monitors!(nodes[0], 1);
6422 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6426 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6427 //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.
6429 let chanmon_cfgs = create_chanmon_cfgs(2);
6430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6433 create_announced_chan_between_nodes(&nodes, 0, 1);
6435 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6437 nodes[1].node.claim_funds(our_payment_preimage);
6438 check_added_monitors!(nodes[1], 1);
6439 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6441 let events = nodes[1].node.get_and_clear_pending_msg_events();
6442 assert_eq!(events.len(), 1);
6443 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6445 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, .. } } => {
6446 assert!(update_add_htlcs.is_empty());
6447 assert_eq!(update_fulfill_htlcs.len(), 1);
6448 assert!(update_fail_htlcs.is_empty());
6449 assert!(update_fail_malformed_htlcs.is_empty());
6450 assert!(update_fee.is_none());
6451 update_fulfill_htlcs[0].clone()
6453 _ => panic!("Unexpected event"),
6457 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6459 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6461 assert!(nodes[0].node.list_channels().is_empty());
6462 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6463 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6464 check_added_monitors!(nodes[0], 1);
6465 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6469 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6470 //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.
6472 let chanmon_cfgs = create_chanmon_cfgs(2);
6473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6475 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6476 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6478 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6479 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6480 check_added_monitors!(nodes[0], 1);
6482 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6483 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6485 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6486 check_added_monitors!(nodes[1], 0);
6487 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6489 let events = nodes[1].node.get_and_clear_pending_msg_events();
6491 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6493 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, .. } } => {
6494 assert!(update_add_htlcs.is_empty());
6495 assert!(update_fulfill_htlcs.is_empty());
6496 assert!(update_fail_htlcs.is_empty());
6497 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6498 assert!(update_fee.is_none());
6499 update_fail_malformed_htlcs[0].clone()
6501 _ => panic!("Unexpected event"),
6504 update_msg.failure_code &= !0x8000;
6505 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6507 assert!(nodes[0].node.list_channels().is_empty());
6508 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6509 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6510 check_added_monitors!(nodes[0], 1);
6511 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6515 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6516 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6517 // * 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.
6519 let chanmon_cfgs = create_chanmon_cfgs(3);
6520 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6521 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6522 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6523 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6524 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6526 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6529 let mut payment_event = {
6530 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6531 check_added_monitors!(nodes[0], 1);
6532 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6533 assert_eq!(events.len(), 1);
6534 SendEvent::from_event(events.remove(0))
6536 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6537 check_added_monitors!(nodes[1], 0);
6538 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6539 expect_pending_htlcs_forwardable!(nodes[1]);
6540 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6541 assert_eq!(events_2.len(), 1);
6542 check_added_monitors!(nodes[1], 1);
6543 payment_event = SendEvent::from_event(events_2.remove(0));
6544 assert_eq!(payment_event.msgs.len(), 1);
6547 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6548 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6549 check_added_monitors!(nodes[2], 0);
6550 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6552 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6553 assert_eq!(events_3.len(), 1);
6554 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6556 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 } } => {
6557 assert!(update_add_htlcs.is_empty());
6558 assert!(update_fulfill_htlcs.is_empty());
6559 assert!(update_fail_htlcs.is_empty());
6560 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6561 assert!(update_fee.is_none());
6562 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6564 _ => panic!("Unexpected event"),
6568 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6570 check_added_monitors!(nodes[1], 0);
6571 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6572 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 }]);
6573 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6574 assert_eq!(events_4.len(), 1);
6576 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6578 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, .. } } => {
6579 assert!(update_add_htlcs.is_empty());
6580 assert!(update_fulfill_htlcs.is_empty());
6581 assert_eq!(update_fail_htlcs.len(), 1);
6582 assert!(update_fail_malformed_htlcs.is_empty());
6583 assert!(update_fee.is_none());
6585 _ => panic!("Unexpected event"),
6588 check_added_monitors!(nodes[1], 1);
6592 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6593 let chanmon_cfgs = create_chanmon_cfgs(3);
6594 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6595 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6596 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6597 create_announced_chan_between_nodes(&nodes, 0, 1);
6598 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6600 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6603 let mut payment_event = {
6604 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6605 check_added_monitors!(nodes[0], 1);
6606 SendEvent::from_node(&nodes[0])
6609 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6610 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6611 expect_pending_htlcs_forwardable!(nodes[1]);
6612 check_added_monitors!(nodes[1], 1);
6613 payment_event = SendEvent::from_node(&nodes[1]);
6614 assert_eq!(payment_event.msgs.len(), 1);
6617 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6618 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6619 check_added_monitors!(nodes[2], 0);
6620 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6622 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6623 assert_eq!(events_3.len(), 1);
6625 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6626 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6627 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6628 update_msg.failure_code |= 0x2000;
6630 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6631 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6633 _ => panic!("Unexpected event"),
6636 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6637 vec![HTLCDestination::NextHopChannel {
6638 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6639 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6640 assert_eq!(events_4.len(), 1);
6641 check_added_monitors!(nodes[1], 1);
6644 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6645 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6646 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6648 _ => panic!("Unexpected event"),
6651 let events_5 = nodes[0].node.get_and_clear_pending_events();
6652 assert_eq!(events_5.len(), 1);
6654 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6655 // the node originating the error to its next hop.
6657 Event::PaymentPathFailed { network_update:
6658 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
6660 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6661 assert!(is_permanent);
6662 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6664 _ => panic!("Unexpected event"),
6667 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6670 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6671 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6672 // 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
6673 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6675 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6676 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6680 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6682 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6683 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6685 // We route 2 dust-HTLCs between A and B
6686 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6687 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6688 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6690 // Cache one local commitment tx as previous
6691 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6693 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6694 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6695 check_added_monitors!(nodes[1], 0);
6696 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6697 check_added_monitors!(nodes[1], 1);
6699 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6700 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6701 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6702 check_added_monitors!(nodes[0], 1);
6704 // Cache one local commitment tx as lastest
6705 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6707 let events = nodes[0].node.get_and_clear_pending_msg_events();
6709 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6710 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6712 _ => panic!("Unexpected event"),
6715 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6716 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6718 _ => panic!("Unexpected event"),
6721 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6722 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6723 if announce_latest {
6724 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6726 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6729 check_closed_broadcast!(nodes[0], true);
6730 check_added_monitors!(nodes[0], 1);
6731 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6733 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6734 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6735 let events = nodes[0].node.get_and_clear_pending_events();
6736 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6737 assert_eq!(events.len(), 2);
6738 let mut first_failed = false;
6739 for event in events {
6741 Event::PaymentPathFailed { payment_hash, .. } => {
6742 if payment_hash == payment_hash_1 {
6743 assert!(!first_failed);
6744 first_failed = true;
6746 assert_eq!(payment_hash, payment_hash_2);
6749 _ => panic!("Unexpected event"),
6755 fn test_failure_delay_dust_htlc_local_commitment() {
6756 do_test_failure_delay_dust_htlc_local_commitment(true);
6757 do_test_failure_delay_dust_htlc_local_commitment(false);
6760 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6761 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6762 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6763 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6764 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6765 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6766 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6768 let chanmon_cfgs = create_chanmon_cfgs(3);
6769 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6770 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6771 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6772 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6774 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6775 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6777 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6778 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6780 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6781 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6783 // We revoked bs_commitment_tx
6785 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6786 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6789 let mut timeout_tx = Vec::new();
6791 // We fail dust-HTLC 1 by broadcast of local commitment tx
6792 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6793 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6794 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6795 expect_payment_failed!(nodes[0], dust_hash, false);
6797 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6798 check_closed_broadcast!(nodes[0], true);
6799 check_added_monitors!(nodes[0], 1);
6800 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6801 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6802 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6803 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6804 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6805 mine_transaction(&nodes[0], &timeout_tx[0]);
6806 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6807 expect_payment_failed!(nodes[0], non_dust_hash, false);
6809 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6810 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6811 check_closed_broadcast!(nodes[0], true);
6812 check_added_monitors!(nodes[0], 1);
6813 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6814 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6816 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6817 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6818 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6819 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6820 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6821 // dust HTLC should have been failed.
6822 expect_payment_failed!(nodes[0], dust_hash, false);
6825 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6827 assert_eq!(timeout_tx[0].lock_time.0, 0);
6829 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6830 mine_transaction(&nodes[0], &timeout_tx[0]);
6831 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6832 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6833 expect_payment_failed!(nodes[0], non_dust_hash, false);
6838 fn test_sweep_outbound_htlc_failure_update() {
6839 do_test_sweep_outbound_htlc_failure_update(false, true);
6840 do_test_sweep_outbound_htlc_failure_update(false, false);
6841 do_test_sweep_outbound_htlc_failure_update(true, false);
6845 fn test_user_configurable_csv_delay() {
6846 // We test our channel constructors yield errors when we pass them absurd csv delay
6848 let mut low_our_to_self_config = UserConfig::default();
6849 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6850 let mut high_their_to_self_config = UserConfig::default();
6851 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6852 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6853 let chanmon_cfgs = create_chanmon_cfgs(2);
6854 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6855 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6856 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6858 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6859 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6860 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6861 &low_our_to_self_config, 0, 42)
6864 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())); },
6865 _ => panic!("Unexpected event"),
6867 } else { assert!(false) }
6869 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6870 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6871 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6872 open_channel.to_self_delay = 200;
6873 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6874 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
6875 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6878 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())); },
6879 _ => panic!("Unexpected event"),
6881 } else { assert!(false); }
6883 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6884 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6885 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6886 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6887 accept_channel.to_self_delay = 200;
6888 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6890 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6892 &ErrorAction::SendErrorMessage { ref msg } => {
6893 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()));
6894 reason_msg = msg.data.clone();
6898 } else { panic!(); }
6899 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6901 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6902 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6903 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6904 open_channel.to_self_delay = 200;
6905 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6906 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
6907 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6910 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())); },
6911 _ => panic!("Unexpected event"),
6913 } else { assert!(false); }
6917 fn test_check_htlc_underpaying() {
6918 // Send payment through A -> B but A is maliciously
6919 // sending a probe payment (i.e less than expected value0
6920 // to B, B should refuse payment.
6922 let chanmon_cfgs = create_chanmon_cfgs(2);
6923 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6924 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6925 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6927 // Create some initial channels
6928 create_announced_chan_between_nodes(&nodes, 0, 1);
6930 let scorer = test_utils::TestScorer::with_penalty(0);
6931 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6932 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(nodes[1].node.invoice_features());
6933 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();
6934 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6935 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6936 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6937 check_added_monitors!(nodes[0], 1);
6939 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6940 assert_eq!(events.len(), 1);
6941 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6942 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6943 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6945 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6946 // and then will wait a second random delay before failing the HTLC back:
6947 expect_pending_htlcs_forwardable!(nodes[1]);
6948 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6950 // Node 3 is expecting payment of 100_000 but received 10_000,
6951 // it should fail htlc like we didn't know the preimage.
6952 nodes[1].node.process_pending_htlc_forwards();
6954 let events = nodes[1].node.get_and_clear_pending_msg_events();
6955 assert_eq!(events.len(), 1);
6956 let (update_fail_htlc, commitment_signed) = match events[0] {
6957 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 } } => {
6958 assert!(update_add_htlcs.is_empty());
6959 assert!(update_fulfill_htlcs.is_empty());
6960 assert_eq!(update_fail_htlcs.len(), 1);
6961 assert!(update_fail_malformed_htlcs.is_empty());
6962 assert!(update_fee.is_none());
6963 (update_fail_htlcs[0].clone(), commitment_signed)
6965 _ => panic!("Unexpected event"),
6967 check_added_monitors!(nodes[1], 1);
6969 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6970 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6972 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
6973 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
6974 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
6975 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6979 fn test_announce_disable_channels() {
6980 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
6981 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6983 let chanmon_cfgs = create_chanmon_cfgs(2);
6984 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6985 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6986 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6988 create_announced_chan_between_nodes(&nodes, 0, 1);
6989 create_announced_chan_between_nodes(&nodes, 1, 0);
6990 create_announced_chan_between_nodes(&nodes, 0, 1);
6993 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6994 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6996 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
6997 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
6998 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6999 assert_eq!(msg_events.len(), 3);
7000 let mut chans_disabled = HashMap::new();
7001 for e in msg_events {
7003 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7004 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7005 // Check that each channel gets updated exactly once
7006 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7007 panic!("Generated ChannelUpdate for wrong chan!");
7010 _ => panic!("Unexpected event"),
7014 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
7015 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7016 assert_eq!(reestablish_1.len(), 3);
7017 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
7018 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7019 assert_eq!(reestablish_2.len(), 3);
7021 // Reestablish chan_1
7022 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7023 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7024 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7025 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7026 // Reestablish chan_2
7027 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7028 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7029 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7030 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7031 // Reestablish chan_3
7032 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7033 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7034 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7035 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7037 nodes[0].node.timer_tick_occurred();
7038 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7039 nodes[0].node.timer_tick_occurred();
7040 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7041 assert_eq!(msg_events.len(), 3);
7042 for e in msg_events {
7044 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7045 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7046 match chans_disabled.remove(&msg.contents.short_channel_id) {
7047 // Each update should have a higher timestamp than the previous one, replacing
7049 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7050 None => panic!("Generated ChannelUpdate for wrong chan!"),
7053 _ => panic!("Unexpected event"),
7056 // Check that each channel gets updated exactly once
7057 assert!(chans_disabled.is_empty());
7061 fn test_bump_penalty_txn_on_revoked_commitment() {
7062 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7063 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7065 let chanmon_cfgs = create_chanmon_cfgs(2);
7066 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7067 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7068 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7070 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7072 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7073 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7074 .with_features(nodes[0].node.invoice_features());
7075 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7076 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7078 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7079 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7080 assert_eq!(revoked_txn[0].output.len(), 4);
7081 assert_eq!(revoked_txn[0].input.len(), 1);
7082 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7083 let revoked_txid = revoked_txn[0].txid();
7085 let mut penalty_sum = 0;
7086 for outp in revoked_txn[0].output.iter() {
7087 if outp.script_pubkey.is_v0_p2wsh() {
7088 penalty_sum += outp.value;
7092 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7093 let header_114 = connect_blocks(&nodes[1], 14);
7095 // Actually revoke tx by claiming a HTLC
7096 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7097 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7098 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7099 check_added_monitors!(nodes[1], 1);
7101 // One or more justice tx should have been broadcast, check it
7105 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7106 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7107 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7108 assert_eq!(node_txn[0].output.len(), 1);
7109 check_spends!(node_txn[0], revoked_txn[0]);
7110 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7111 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7112 penalty_1 = node_txn[0].txid();
7116 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7117 connect_blocks(&nodes[1], 15);
7118 let mut penalty_2 = penalty_1;
7119 let mut feerate_2 = 0;
7121 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7122 assert_eq!(node_txn.len(), 1);
7123 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7124 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7125 assert_eq!(node_txn[0].output.len(), 1);
7126 check_spends!(node_txn[0], revoked_txn[0]);
7127 penalty_2 = node_txn[0].txid();
7128 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7129 assert_ne!(penalty_2, penalty_1);
7130 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7131 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7132 // Verify 25% bump heuristic
7133 assert!(feerate_2 * 100 >= feerate_1 * 125);
7137 assert_ne!(feerate_2, 0);
7139 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7140 connect_blocks(&nodes[1], 1);
7142 let mut feerate_3 = 0;
7144 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7145 assert_eq!(node_txn.len(), 1);
7146 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7147 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7148 assert_eq!(node_txn[0].output.len(), 1);
7149 check_spends!(node_txn[0], revoked_txn[0]);
7150 penalty_3 = node_txn[0].txid();
7151 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7152 assert_ne!(penalty_3, penalty_2);
7153 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7154 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7155 // Verify 25% bump heuristic
7156 assert!(feerate_3 * 100 >= feerate_2 * 125);
7160 assert_ne!(feerate_3, 0);
7162 nodes[1].node.get_and_clear_pending_events();
7163 nodes[1].node.get_and_clear_pending_msg_events();
7167 fn test_bump_penalty_txn_on_revoked_htlcs() {
7168 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7169 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7171 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7172 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7177 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7178 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7179 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(nodes[1].node.invoice_features());
7180 let scorer = test_utils::TestScorer::with_penalty(0);
7181 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7182 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7183 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7184 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7185 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(nodes[0].node.invoice_features());
7186 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7187 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7188 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7190 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7191 assert_eq!(revoked_local_txn[0].input.len(), 1);
7192 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7194 // Revoke local commitment tx
7195 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7197 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7198 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7199 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7200 check_closed_broadcast!(nodes[1], true);
7201 check_added_monitors!(nodes[1], 1);
7202 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7203 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7205 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7206 assert_eq!(revoked_htlc_txn.len(), 2);
7208 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7209 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7210 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7212 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7213 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7214 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7215 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7217 // Broadcast set of revoked txn on A
7218 let hash_128 = connect_blocks(&nodes[0], 40);
7219 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7220 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7221 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7222 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7223 let events = nodes[0].node.get_and_clear_pending_events();
7224 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7225 match events.last().unwrap() {
7226 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7227 _ => panic!("Unexpected event"),
7233 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7234 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7235 // Verify claim tx are spending revoked HTLC txn
7237 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7238 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7239 // which are included in the same block (they are broadcasted because we scan the
7240 // transactions linearly and generate claims as we go, they likely should be removed in the
7242 assert_eq!(node_txn[0].input.len(), 1);
7243 check_spends!(node_txn[0], revoked_local_txn[0]);
7244 assert_eq!(node_txn[1].input.len(), 1);
7245 check_spends!(node_txn[1], revoked_local_txn[0]);
7246 assert_eq!(node_txn[2].input.len(), 1);
7247 check_spends!(node_txn[2], revoked_local_txn[0]);
7249 // Each of the three justice transactions claim a separate (single) output of the three
7250 // available, which we check here:
7251 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7252 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7253 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7255 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7256 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7258 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7259 // output, checked above).
7260 assert_eq!(node_txn[3].input.len(), 2);
7261 assert_eq!(node_txn[3].output.len(), 1);
7262 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7264 first = node_txn[3].txid();
7265 // Store both feerates for later comparison
7266 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7267 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7268 penalty_txn = vec![node_txn[2].clone()];
7272 // Connect one more block to see if bumped penalty are issued for HTLC txn
7273 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7274 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7275 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7276 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7278 // Few more blocks to confirm penalty txn
7279 connect_blocks(&nodes[0], 4);
7280 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7281 let header_144 = connect_blocks(&nodes[0], 9);
7283 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7284 assert_eq!(node_txn.len(), 1);
7286 assert_eq!(node_txn[0].input.len(), 2);
7287 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7288 // Verify bumped tx is different and 25% bump heuristic
7289 assert_ne!(first, node_txn[0].txid());
7290 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7291 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7292 assert!(feerate_2 * 100 > feerate_1 * 125);
7293 let txn = vec![node_txn[0].clone()];
7297 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7298 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7299 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7300 connect_blocks(&nodes[0], 20);
7302 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7303 // We verify than no new transaction has been broadcast because previously
7304 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7305 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7306 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7307 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7308 // up bumped justice generation.
7309 assert_eq!(node_txn.len(), 0);
7312 check_closed_broadcast!(nodes[0], true);
7313 check_added_monitors!(nodes[0], 1);
7317 fn test_bump_penalty_txn_on_remote_commitment() {
7318 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7319 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7322 // Provide preimage for one
7323 // Check aggregation
7325 let chanmon_cfgs = create_chanmon_cfgs(2);
7326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7328 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7330 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7331 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7332 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7334 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7335 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7336 assert_eq!(remote_txn[0].output.len(), 4);
7337 assert_eq!(remote_txn[0].input.len(), 1);
7338 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7340 // Claim a HTLC without revocation (provide B monitor with preimage)
7341 nodes[1].node.claim_funds(payment_preimage);
7342 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7343 mine_transaction(&nodes[1], &remote_txn[0]);
7344 check_added_monitors!(nodes[1], 2);
7345 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7347 // One or more claim tx should have been broadcast, check it
7351 let feerate_timeout;
7352 let feerate_preimage;
7354 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7355 // 3 transactions including:
7356 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7357 assert_eq!(node_txn.len(), 3);
7358 assert_eq!(node_txn[0].input.len(), 1);
7359 assert_eq!(node_txn[1].input.len(), 1);
7360 assert_eq!(node_txn[2].input.len(), 1);
7361 check_spends!(node_txn[0], remote_txn[0]);
7362 check_spends!(node_txn[1], remote_txn[0]);
7363 check_spends!(node_txn[2], remote_txn[0]);
7365 preimage = node_txn[0].txid();
7366 let index = node_txn[0].input[0].previous_output.vout;
7367 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7368 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7370 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7371 (node_txn[2].clone(), node_txn[1].clone())
7373 (node_txn[1].clone(), node_txn[2].clone())
7376 preimage_bump = preimage_bump_tx;
7377 check_spends!(preimage_bump, remote_txn[0]);
7378 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7380 timeout = timeout_tx.txid();
7381 let index = timeout_tx.input[0].previous_output.vout;
7382 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7383 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7387 assert_ne!(feerate_timeout, 0);
7388 assert_ne!(feerate_preimage, 0);
7390 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7391 connect_blocks(&nodes[1], 15);
7393 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7394 assert_eq!(node_txn.len(), 1);
7395 assert_eq!(node_txn[0].input.len(), 1);
7396 assert_eq!(preimage_bump.input.len(), 1);
7397 check_spends!(node_txn[0], remote_txn[0]);
7398 check_spends!(preimage_bump, remote_txn[0]);
7400 let index = preimage_bump.input[0].previous_output.vout;
7401 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7402 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7403 assert!(new_feerate * 100 > feerate_timeout * 125);
7404 assert_ne!(timeout, preimage_bump.txid());
7406 let index = node_txn[0].input[0].previous_output.vout;
7407 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7408 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7409 assert!(new_feerate * 100 > feerate_preimage * 125);
7410 assert_ne!(preimage, node_txn[0].txid());
7415 nodes[1].node.get_and_clear_pending_events();
7416 nodes[1].node.get_and_clear_pending_msg_events();
7420 fn test_counterparty_raa_skip_no_crash() {
7421 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7422 // commitment transaction, we would have happily carried on and provided them the next
7423 // commitment transaction based on one RAA forward. This would probably eventually have led to
7424 // channel closure, but it would not have resulted in funds loss. Still, our
7425 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7426 // check simply that the channel is closed in response to such an RAA, but don't check whether
7427 // we decide to punish our counterparty for revoking their funds (as we don't currently
7429 let chanmon_cfgs = create_chanmon_cfgs(2);
7430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7433 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7435 let per_commitment_secret;
7436 let next_per_commitment_point;
7438 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7439 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7440 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7442 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7444 // Make signer believe we got a counterparty signature, so that it allows the revocation
7445 keys.get_enforcement_state().last_holder_commitment -= 1;
7446 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7448 // Must revoke without gaps
7449 keys.get_enforcement_state().last_holder_commitment -= 1;
7450 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7452 keys.get_enforcement_state().last_holder_commitment -= 1;
7453 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7454 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7457 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7458 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7459 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7460 check_added_monitors!(nodes[1], 1);
7461 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7465 fn test_bump_txn_sanitize_tracking_maps() {
7466 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7467 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7469 let chanmon_cfgs = create_chanmon_cfgs(2);
7470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7472 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7474 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7475 // Lock HTLC in both directions
7476 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7477 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7479 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7480 assert_eq!(revoked_local_txn[0].input.len(), 1);
7481 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7483 // Revoke local commitment tx
7484 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7486 // Broadcast set of revoked txn on A
7487 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7488 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7489 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7491 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7492 check_closed_broadcast!(nodes[0], true);
7493 check_added_monitors!(nodes[0], 1);
7494 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7496 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7497 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7498 check_spends!(node_txn[0], revoked_local_txn[0]);
7499 check_spends!(node_txn[1], revoked_local_txn[0]);
7500 check_spends!(node_txn[2], revoked_local_txn[0]);
7501 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7505 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7506 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7507 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7509 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7510 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7511 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7516 fn test_pending_claimed_htlc_no_balance_underflow() {
7517 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7518 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7519 let chanmon_cfgs = create_chanmon_cfgs(2);
7520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7523 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7525 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7526 nodes[1].node.claim_funds(payment_preimage);
7527 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7528 check_added_monitors!(nodes[1], 1);
7529 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7531 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7532 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7533 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7534 check_added_monitors!(nodes[0], 1);
7535 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7537 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7538 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7539 // can get our balance.
7541 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7542 // the public key of the only hop. This works around ChannelDetails not showing the
7543 // almost-claimed HTLC as available balance.
7544 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7545 route.payment_params = None; // This is all wrong, but unnecessary
7546 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7547 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7548 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7550 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7554 fn test_channel_conf_timeout() {
7555 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7556 // confirm within 2016 blocks, as recommended by BOLT 2.
7557 let chanmon_cfgs = create_chanmon_cfgs(2);
7558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7560 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7562 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7564 // The outbound node should wait forever for confirmation:
7565 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7566 // copied here instead of directly referencing the constant.
7567 connect_blocks(&nodes[0], 2016);
7568 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7570 // The inbound node should fail the channel after exactly 2016 blocks
7571 connect_blocks(&nodes[1], 2015);
7572 check_added_monitors!(nodes[1], 0);
7573 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7575 connect_blocks(&nodes[1], 1);
7576 check_added_monitors!(nodes[1], 1);
7577 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7578 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7579 assert_eq!(close_ev.len(), 1);
7581 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7582 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7583 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7585 _ => panic!("Unexpected event"),
7590 fn test_override_channel_config() {
7591 let chanmon_cfgs = create_chanmon_cfgs(2);
7592 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7593 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7594 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7596 // Node0 initiates a channel to node1 using the override config.
7597 let mut override_config = UserConfig::default();
7598 override_config.channel_handshake_config.our_to_self_delay = 200;
7600 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7602 // Assert the channel created by node0 is using the override config.
7603 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7604 assert_eq!(res.channel_flags, 0);
7605 assert_eq!(res.to_self_delay, 200);
7609 fn test_override_0msat_htlc_minimum() {
7610 let mut zero_config = UserConfig::default();
7611 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7612 let chanmon_cfgs = create_chanmon_cfgs(2);
7613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7617 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7618 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7619 assert_eq!(res.htlc_minimum_msat, 1);
7621 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7622 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7623 assert_eq!(res.htlc_minimum_msat, 1);
7627 fn test_channel_update_has_correct_htlc_maximum_msat() {
7628 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7629 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7630 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7631 // 90% of the `channel_value`.
7632 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7634 let mut config_30_percent = UserConfig::default();
7635 config_30_percent.channel_handshake_config.announced_channel = true;
7636 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7637 let mut config_50_percent = UserConfig::default();
7638 config_50_percent.channel_handshake_config.announced_channel = true;
7639 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7640 let mut config_95_percent = UserConfig::default();
7641 config_95_percent.channel_handshake_config.announced_channel = true;
7642 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7643 let mut config_100_percent = UserConfig::default();
7644 config_100_percent.channel_handshake_config.announced_channel = true;
7645 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7647 let chanmon_cfgs = create_chanmon_cfgs(4);
7648 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7649 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)]);
7650 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7652 let channel_value_satoshis = 100000;
7653 let channel_value_msat = channel_value_satoshis * 1000;
7654 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7655 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7656 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7658 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7659 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7661 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7662 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7663 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7664 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7665 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7666 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7668 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7669 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7671 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7672 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7673 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7675 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7679 fn test_manually_accept_inbound_channel_request() {
7680 let mut manually_accept_conf = UserConfig::default();
7681 manually_accept_conf.manually_accept_inbound_channels = true;
7682 let chanmon_cfgs = create_chanmon_cfgs(2);
7683 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7684 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7685 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7687 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7688 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7690 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7692 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7693 // accepting the inbound channel request.
7694 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7696 let events = nodes[1].node.get_and_clear_pending_events();
7698 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7699 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7701 _ => panic!("Unexpected event"),
7704 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7705 assert_eq!(accept_msg_ev.len(), 1);
7707 match accept_msg_ev[0] {
7708 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7709 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7711 _ => panic!("Unexpected event"),
7714 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7716 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7717 assert_eq!(close_msg_ev.len(), 1);
7719 let events = nodes[1].node.get_and_clear_pending_events();
7721 Event::ChannelClosed { user_channel_id, .. } => {
7722 assert_eq!(user_channel_id, 23);
7724 _ => panic!("Unexpected event"),
7729 fn test_manually_reject_inbound_channel_request() {
7730 let mut manually_accept_conf = UserConfig::default();
7731 manually_accept_conf.manually_accept_inbound_channels = true;
7732 let chanmon_cfgs = create_chanmon_cfgs(2);
7733 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7734 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7735 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7737 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7738 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7740 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7742 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7743 // rejecting the inbound channel request.
7744 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7746 let events = nodes[1].node.get_and_clear_pending_events();
7748 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7749 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7751 _ => panic!("Unexpected event"),
7754 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7755 assert_eq!(close_msg_ev.len(), 1);
7757 match close_msg_ev[0] {
7758 MessageSendEvent::HandleError { ref node_id, .. } => {
7759 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7761 _ => panic!("Unexpected event"),
7763 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7767 fn test_reject_funding_before_inbound_channel_accepted() {
7768 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7769 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7770 // the node operator before the counterparty sends a `FundingCreated` message. If a
7771 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7772 // and the channel should be closed.
7773 let mut manually_accept_conf = UserConfig::default();
7774 manually_accept_conf.manually_accept_inbound_channels = true;
7775 let chanmon_cfgs = create_chanmon_cfgs(2);
7776 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7777 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7778 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7780 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7781 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7782 let temp_channel_id = res.temporary_channel_id;
7784 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7786 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7787 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7789 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7790 nodes[1].node.get_and_clear_pending_events();
7792 // Get the `AcceptChannel` message of `nodes[1]` without calling
7793 // `ChannelManager::accept_inbound_channel`, which generates a
7794 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7795 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7796 // succeed when `nodes[0]` is passed to it.
7797 let accept_chan_msg = {
7798 let mut node_1_per_peer_lock;
7799 let mut node_1_peer_state_lock;
7800 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7801 channel.get_accept_channel_message()
7803 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7805 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7807 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7808 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7810 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7811 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7813 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7814 assert_eq!(close_msg_ev.len(), 1);
7816 let expected_err = "FundingCreated message received before the channel was accepted";
7817 match close_msg_ev[0] {
7818 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7819 assert_eq!(msg.channel_id, temp_channel_id);
7820 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7821 assert_eq!(msg.data, expected_err);
7823 _ => panic!("Unexpected event"),
7826 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7830 fn test_can_not_accept_inbound_channel_twice() {
7831 let mut manually_accept_conf = UserConfig::default();
7832 manually_accept_conf.manually_accept_inbound_channels = true;
7833 let chanmon_cfgs = create_chanmon_cfgs(2);
7834 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7835 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7836 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7838 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7839 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7841 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7843 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7844 // accepting the inbound channel request.
7845 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7847 let events = nodes[1].node.get_and_clear_pending_events();
7849 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7850 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7851 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7853 Err(APIError::APIMisuseError { err }) => {
7854 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7856 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7857 Err(_) => panic!("Unexpected Error"),
7860 _ => panic!("Unexpected event"),
7863 // Ensure that the channel wasn't closed after attempting to accept it twice.
7864 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7865 assert_eq!(accept_msg_ev.len(), 1);
7867 match accept_msg_ev[0] {
7868 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7869 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7871 _ => panic!("Unexpected event"),
7876 fn test_can_not_accept_unknown_inbound_channel() {
7877 let chanmon_cfg = create_chanmon_cfgs(2);
7878 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7879 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7880 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7882 let unknown_channel_id = [0; 32];
7883 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7885 Err(APIError::ChannelUnavailable { err }) => {
7886 assert_eq!(err, format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(unknown_channel_id), nodes[1].node.get_our_node_id()));
7888 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7889 Err(_) => panic!("Unexpected Error"),
7894 fn test_simple_mpp() {
7895 // Simple test of sending a multi-path payment.
7896 let chanmon_cfgs = create_chanmon_cfgs(4);
7897 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7898 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7899 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7901 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7902 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7903 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7904 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7906 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7907 let path = route.paths[0].clone();
7908 route.paths.push(path);
7909 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7910 route.paths[0][0].short_channel_id = chan_1_id;
7911 route.paths[0][1].short_channel_id = chan_3_id;
7912 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7913 route.paths[1][0].short_channel_id = chan_2_id;
7914 route.paths[1][1].short_channel_id = chan_4_id;
7915 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7916 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7920 fn test_preimage_storage() {
7921 // Simple test of payment preimage storage allowing no client-side storage to claim payments
7922 let chanmon_cfgs = create_chanmon_cfgs(2);
7923 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7924 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7925 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7927 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7930 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
7931 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7932 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7933 check_added_monitors!(nodes[0], 1);
7934 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7935 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7936 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7937 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7939 // Note that after leaving the above scope we have no knowledge of any arguments or return
7940 // values from previous calls.
7941 expect_pending_htlcs_forwardable!(nodes[1]);
7942 let events = nodes[1].node.get_and_clear_pending_events();
7943 assert_eq!(events.len(), 1);
7945 Event::PaymentClaimable { ref purpose, .. } => {
7947 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7948 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7950 _ => panic!("expected PaymentPurpose::InvoicePayment")
7953 _ => panic!("Unexpected event"),
7958 #[allow(deprecated)]
7959 fn test_secret_timeout() {
7960 // Simple test of payment secret storage time outs. After
7961 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7962 let chanmon_cfgs = create_chanmon_cfgs(2);
7963 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7964 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7965 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7967 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7969 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
7971 // We should fail to register the same payment hash twice, at least until we've connected a
7972 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
7973 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7974 assert_eq!(err, "Duplicate payment hash");
7975 } else { panic!(); }
7977 let node_1_blocks = nodes[1].blocks.lock().unwrap();
7979 header: BlockHeader {
7981 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
7982 merkle_root: TxMerkleNode::all_zeros(),
7983 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
7987 connect_block(&nodes[1], &block);
7988 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7989 assert_eq!(err, "Duplicate payment hash");
7990 } else { panic!(); }
7992 // If we then connect the second block, we should be able to register the same payment hash
7993 // again (this time getting a new payment secret).
7994 block.header.prev_blockhash = block.header.block_hash();
7995 block.header.time += 1;
7996 connect_block(&nodes[1], &block);
7997 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
7998 assert_ne!(payment_secret_1, our_payment_secret);
8001 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8002 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8003 check_added_monitors!(nodes[0], 1);
8004 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8005 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8006 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8007 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8009 // Note that after leaving the above scope we have no knowledge of any arguments or return
8010 // values from previous calls.
8011 expect_pending_htlcs_forwardable!(nodes[1]);
8012 let events = nodes[1].node.get_and_clear_pending_events();
8013 assert_eq!(events.len(), 1);
8015 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8016 assert!(payment_preimage.is_none());
8017 assert_eq!(payment_secret, our_payment_secret);
8018 // We don't actually have the payment preimage with which to claim this payment!
8020 _ => panic!("Unexpected event"),
8025 fn test_bad_secret_hash() {
8026 // Simple test of unregistered payment hash/invalid payment secret handling
8027 let chanmon_cfgs = create_chanmon_cfgs(2);
8028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8030 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8032 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8034 let random_payment_hash = PaymentHash([42; 32]);
8035 let random_payment_secret = PaymentSecret([43; 32]);
8036 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8037 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8039 // All the below cases should end up being handled exactly identically, so we macro the
8040 // resulting events.
8041 macro_rules! handle_unknown_invalid_payment_data {
8042 ($payment_hash: expr) => {
8043 check_added_monitors!(nodes[0], 1);
8044 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8045 let payment_event = SendEvent::from_event(events.pop().unwrap());
8046 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8047 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8049 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8050 // again to process the pending backwards-failure of the HTLC
8051 expect_pending_htlcs_forwardable!(nodes[1]);
8052 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8053 check_added_monitors!(nodes[1], 1);
8055 // We should fail the payment back
8056 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8057 match events.pop().unwrap() {
8058 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8059 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8060 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8062 _ => panic!("Unexpected event"),
8067 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8068 // Error data is the HTLC value (100,000) and current block height
8069 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8071 // Send a payment with the right payment hash but the wrong payment secret
8072 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8073 handle_unknown_invalid_payment_data!(our_payment_hash);
8074 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8076 // Send a payment with a random payment hash, but the right payment secret
8077 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8078 handle_unknown_invalid_payment_data!(random_payment_hash);
8079 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8081 // Send a payment with a random payment hash and random payment secret
8082 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_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);
8088 fn test_update_err_monitor_lockdown() {
8089 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8090 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8091 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8094 // This scenario may happen in a watchtower setup, where watchtower process a block height
8095 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8096 // commitment at same time.
8098 let chanmon_cfgs = create_chanmon_cfgs(2);
8099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8101 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8103 // Create some initial channel
8104 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8105 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8107 // Rebalance the network to generate htlc in the two directions
8108 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8110 // Route a HTLC from node 0 to node 1 (but don't settle)
8111 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8113 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8114 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8115 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8116 let persister = test_utils::TestPersister::new();
8118 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8119 let mut w = test_utils::TestVecWriter(Vec::new());
8120 monitor.write(&mut w).unwrap();
8121 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8122 &mut io::Cursor::new(&w.0), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8123 assert!(new_monitor == *monitor);
8124 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);
8125 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8128 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8129 let block = Block { header, txdata: vec![] };
8130 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8131 // transaction lock time requirements here.
8132 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8133 watchtower.chain_monitor.block_connected(&block, 200);
8135 // Try to update ChannelMonitor
8136 nodes[1].node.claim_funds(preimage);
8137 check_added_monitors!(nodes[1], 1);
8138 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8140 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8141 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8142 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8144 let mut node_0_per_peer_lock;
8145 let mut node_0_peer_state_lock;
8146 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8147 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8148 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8149 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8150 } else { assert!(false); }
8152 // Our local monitor is in-sync and hasn't processed yet timeout
8153 check_added_monitors!(nodes[0], 1);
8154 let events = nodes[0].node.get_and_clear_pending_events();
8155 assert_eq!(events.len(), 1);
8159 fn test_concurrent_monitor_claim() {
8160 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8161 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8162 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8163 // state N+1 confirms. Alice claims output from state N+1.
8165 let chanmon_cfgs = create_chanmon_cfgs(2);
8166 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8167 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8168 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8170 // Create some initial channel
8171 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8172 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8174 // Rebalance the network to generate htlc in the two directions
8175 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8177 // Route a HTLC from node 0 to node 1 (but don't settle)
8178 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8180 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8181 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8182 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8183 let persister = test_utils::TestPersister::new();
8184 let watchtower_alice = {
8185 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8186 let mut w = test_utils::TestVecWriter(Vec::new());
8187 monitor.write(&mut w).unwrap();
8188 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8189 &mut io::Cursor::new(&w.0), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8190 assert!(new_monitor == *monitor);
8191 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);
8192 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8195 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8196 let block = Block { header, txdata: vec![] };
8197 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8198 // transaction lock time requirements here.
8199 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));
8200 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8202 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8204 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8205 assert_eq!(txn.len(), 2);
8209 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8210 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8211 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8212 let persister = test_utils::TestPersister::new();
8213 let watchtower_bob = {
8214 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8215 let mut w = test_utils::TestVecWriter(Vec::new());
8216 monitor.write(&mut w).unwrap();
8217 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8218 &mut io::Cursor::new(&w.0), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8219 assert!(new_monitor == *monitor);
8220 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);
8221 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8224 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8225 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8227 // Route another payment to generate another update with still previous HTLC pending
8228 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8230 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8232 check_added_monitors!(nodes[1], 1);
8234 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8235 assert_eq!(updates.update_add_htlcs.len(), 1);
8236 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8238 let mut node_0_per_peer_lock;
8239 let mut node_0_peer_state_lock;
8240 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8241 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8242 // Watchtower Alice should already have seen the block and reject the update
8243 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8244 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8245 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8246 } else { assert!(false); }
8248 // Our local monitor is in-sync and hasn't processed yet timeout
8249 check_added_monitors!(nodes[0], 1);
8251 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8252 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8253 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8255 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8258 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8259 assert_eq!(txn.len(), 2);
8260 bob_state_y = txn[0].clone();
8264 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8265 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8266 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);
8268 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8269 assert_eq!(htlc_txn.len(), 1);
8270 check_spends!(htlc_txn[0], bob_state_y);
8275 fn test_pre_lockin_no_chan_closed_update() {
8276 // Test that if a peer closes a channel in response to a funding_created message we don't
8277 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8280 // Doing so would imply a channel monitor update before the initial channel monitor
8281 // registration, violating our API guarantees.
8283 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8284 // then opening a second channel with the same funding output as the first (which is not
8285 // rejected because the first channel does not exist in the ChannelManager) and closing it
8286 // before receiving funding_signed.
8287 let chanmon_cfgs = create_chanmon_cfgs(2);
8288 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8289 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8290 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8292 // Create an initial channel
8293 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8294 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8295 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8296 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8297 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8299 // Move the first channel through the funding flow...
8300 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8302 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8303 check_added_monitors!(nodes[0], 0);
8305 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8306 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8307 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8308 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8309 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8313 fn test_htlc_no_detection() {
8314 // This test is a mutation to underscore the detection logic bug we had
8315 // before #653. HTLC value routed is above the remaining balance, thus
8316 // inverting HTLC and `to_remote` output. HTLC will come second and
8317 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8318 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8319 // outputs order detection for correct spending children filtring.
8321 let chanmon_cfgs = create_chanmon_cfgs(2);
8322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8324 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8326 // Create some initial channels
8327 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8329 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8330 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8331 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8332 assert_eq!(local_txn[0].input.len(), 1);
8333 assert_eq!(local_txn[0].output.len(), 3);
8334 check_spends!(local_txn[0], chan_1.3);
8336 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8337 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8338 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8339 // We deliberately connect the local tx twice as this should provoke a failure calling
8340 // this test before #653 fix.
8341 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);
8342 check_closed_broadcast!(nodes[0], true);
8343 check_added_monitors!(nodes[0], 1);
8344 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8345 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8347 let htlc_timeout = {
8348 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8349 assert_eq!(node_txn.len(), 1);
8350 assert_eq!(node_txn[0].input.len(), 1);
8351 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8352 check_spends!(node_txn[0], local_txn[0]);
8356 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8357 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8358 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8359 expect_payment_failed!(nodes[0], our_payment_hash, false);
8362 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8363 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8364 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8365 // Carol, Alice would be the upstream node, and Carol the downstream.)
8367 // Steps of the test:
8368 // 1) Alice sends a HTLC to Carol through Bob.
8369 // 2) Carol doesn't settle the HTLC.
8370 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8371 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8372 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8373 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8374 // 5) Carol release the preimage to Bob off-chain.
8375 // 6) Bob claims the offered output on the broadcasted commitment.
8376 let chanmon_cfgs = create_chanmon_cfgs(3);
8377 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8378 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8379 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8381 // Create some initial channels
8382 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8383 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8385 // Steps (1) and (2):
8386 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8387 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8389 // Check that Alice's commitment transaction now contains an output for this HTLC.
8390 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8391 check_spends!(alice_txn[0], chan_ab.3);
8392 assert_eq!(alice_txn[0].output.len(), 2);
8393 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8394 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8395 assert_eq!(alice_txn.len(), 2);
8397 // Steps (3) and (4):
8398 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8399 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8400 let mut force_closing_node = 0; // Alice force-closes
8401 let mut counterparty_node = 1; // Bob if Alice force-closes
8404 if !broadcast_alice {
8405 force_closing_node = 1;
8406 counterparty_node = 0;
8408 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8409 check_closed_broadcast!(nodes[force_closing_node], true);
8410 check_added_monitors!(nodes[force_closing_node], 1);
8411 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8412 if go_onchain_before_fulfill {
8413 let txn_to_broadcast = match broadcast_alice {
8414 true => alice_txn.clone(),
8415 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8417 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8418 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8419 if broadcast_alice {
8420 check_closed_broadcast!(nodes[1], true);
8421 check_added_monitors!(nodes[1], 1);
8422 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8427 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8428 // process of removing the HTLC from their commitment transactions.
8429 nodes[2].node.claim_funds(payment_preimage);
8430 check_added_monitors!(nodes[2], 1);
8431 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8433 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8434 assert!(carol_updates.update_add_htlcs.is_empty());
8435 assert!(carol_updates.update_fail_htlcs.is_empty());
8436 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8437 assert!(carol_updates.update_fee.is_none());
8438 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8440 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8441 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8442 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8443 if !go_onchain_before_fulfill && broadcast_alice {
8444 let events = nodes[1].node.get_and_clear_pending_msg_events();
8445 assert_eq!(events.len(), 1);
8447 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8448 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8450 _ => panic!("Unexpected event"),
8453 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8454 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8455 // Carol<->Bob's updated commitment transaction info.
8456 check_added_monitors!(nodes[1], 2);
8458 let events = nodes[1].node.get_and_clear_pending_msg_events();
8459 assert_eq!(events.len(), 2);
8460 let bob_revocation = match events[0] {
8461 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8462 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8465 _ => panic!("Unexpected event"),
8467 let bob_updates = match events[1] {
8468 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8469 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8472 _ => panic!("Unexpected event"),
8475 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8476 check_added_monitors!(nodes[2], 1);
8477 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8478 check_added_monitors!(nodes[2], 1);
8480 let events = nodes[2].node.get_and_clear_pending_msg_events();
8481 assert_eq!(events.len(), 1);
8482 let carol_revocation = match events[0] {
8483 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8484 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8487 _ => panic!("Unexpected event"),
8489 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8490 check_added_monitors!(nodes[1], 1);
8492 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8493 // here's where we put said channel's commitment tx on-chain.
8494 let mut txn_to_broadcast = alice_txn.clone();
8495 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8496 if !go_onchain_before_fulfill {
8497 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8498 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8499 // If Bob was the one to force-close, he will have already passed these checks earlier.
8500 if broadcast_alice {
8501 check_closed_broadcast!(nodes[1], true);
8502 check_added_monitors!(nodes[1], 1);
8503 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8505 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8506 if broadcast_alice {
8507 assert_eq!(bob_txn.len(), 1);
8508 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8510 assert_eq!(bob_txn.len(), 2);
8511 check_spends!(bob_txn[0], chan_ab.3);
8516 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8517 // broadcasted commitment transaction.
8519 let script_weight = match broadcast_alice {
8520 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8521 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8523 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8524 // Bob force-closed and broadcasts the commitment transaction along with a
8525 // HTLC-output-claiming transaction.
8526 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8527 if broadcast_alice {
8528 assert_eq!(bob_txn.len(), 1);
8529 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8530 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8532 assert_eq!(bob_txn.len(), 2);
8533 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8534 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8540 fn test_onchain_htlc_settlement_after_close() {
8541 do_test_onchain_htlc_settlement_after_close(true, true);
8542 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8543 do_test_onchain_htlc_settlement_after_close(true, false);
8544 do_test_onchain_htlc_settlement_after_close(false, false);
8548 fn test_duplicate_temporary_channel_id_from_different_peers() {
8549 // Tests that we can accept two different `OpenChannel` requests with the same
8550 // `temporary_channel_id`, as long as they are from different peers.
8551 let chanmon_cfgs = create_chanmon_cfgs(3);
8552 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8553 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8554 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8556 // Create an first channel channel
8557 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8558 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8560 // Create an second channel
8561 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8562 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8564 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8565 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8566 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8568 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8569 // `temporary_channel_id` as they are from different peers.
8570 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8572 let events = nodes[0].node.get_and_clear_pending_msg_events();
8573 assert_eq!(events.len(), 1);
8575 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8576 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8577 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8579 _ => panic!("Unexpected event"),
8583 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8585 let events = nodes[0].node.get_and_clear_pending_msg_events();
8586 assert_eq!(events.len(), 1);
8588 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8589 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8590 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8592 _ => panic!("Unexpected event"),
8598 fn test_duplicate_chan_id() {
8599 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8600 // already open we reject it and keep the old channel.
8602 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8603 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8604 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8605 // updating logic for the existing channel.
8606 let chanmon_cfgs = create_chanmon_cfgs(2);
8607 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8608 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8609 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8611 // Create an initial channel
8612 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8613 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8614 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8615 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8617 // Try to create a second channel with the same temporary_channel_id as the first and check
8618 // that it is rejected.
8619 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8621 let events = nodes[1].node.get_and_clear_pending_msg_events();
8622 assert_eq!(events.len(), 1);
8624 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8625 // Technically, at this point, nodes[1] would be justified in thinking both the
8626 // first (valid) and second (invalid) channels are closed, given they both have
8627 // the same non-temporary channel_id. However, currently we do not, so we just
8628 // 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 // Move the first channel through the funding flow...
8637 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8639 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8640 check_added_monitors!(nodes[0], 0);
8642 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8643 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8645 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8646 assert_eq!(added_monitors.len(), 1);
8647 assert_eq!(added_monitors[0].0, funding_output);
8648 added_monitors.clear();
8650 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8652 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8653 let channel_id = funding_outpoint.to_channel_id();
8655 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8658 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8659 // Technically this is allowed by the spec, but we don't support it and there's little reason
8660 // to. Still, it shouldn't cause any other issues.
8661 open_chan_msg.temporary_channel_id = channel_id;
8662 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8664 let events = nodes[1].node.get_and_clear_pending_msg_events();
8665 assert_eq!(events.len(), 1);
8667 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8668 // Technically, at this point, nodes[1] would be justified in thinking both
8669 // channels are closed, but currently we do not, so we just move forward with it.
8670 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8671 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8673 _ => panic!("Unexpected event"),
8677 // Now try to create a second channel which has a duplicate funding output.
8678 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8679 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8680 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8681 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8682 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8684 let funding_created = {
8685 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8686 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8687 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8688 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8689 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8690 // channelmanager in a possibly nonsense state instead).
8691 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8692 let logger = test_utils::TestLogger::new();
8693 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8695 check_added_monitors!(nodes[0], 0);
8696 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8697 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8698 // still needs to be cleared here.
8699 check_added_monitors!(nodes[1], 1);
8701 // ...still, nodes[1] will reject the duplicate channel.
8703 let events = nodes[1].node.get_and_clear_pending_msg_events();
8704 assert_eq!(events.len(), 1);
8706 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8707 // Technically, at this point, nodes[1] would be justified in thinking both
8708 // channels are closed, but currently we do not, so we just move forward with it.
8709 assert_eq!(msg.channel_id, channel_id);
8710 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8712 _ => panic!("Unexpected event"),
8716 // finally, finish creating the original channel and send a payment over it to make sure
8717 // everything is functional.
8718 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8720 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8721 assert_eq!(added_monitors.len(), 1);
8722 assert_eq!(added_monitors[0].0, funding_output);
8723 added_monitors.clear();
8726 let events_4 = nodes[0].node.get_and_clear_pending_events();
8727 assert_eq!(events_4.len(), 0);
8728 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8729 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8731 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8732 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8733 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8735 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8739 fn test_error_chans_closed() {
8740 // Test that we properly handle error messages, closing appropriate channels.
8742 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8743 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8744 // we can test various edge cases around it to ensure we don't regress.
8745 let chanmon_cfgs = create_chanmon_cfgs(3);
8746 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8747 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8748 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8750 // Create some initial channels
8751 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8752 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8753 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8755 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8756 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8757 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8759 // Closing a channel from a different peer has no effect
8760 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8761 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8763 // Closing one channel doesn't impact others
8764 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8765 check_added_monitors!(nodes[0], 1);
8766 check_closed_broadcast!(nodes[0], false);
8767 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8768 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8769 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8770 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);
8771 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);
8773 // A null channel ID should close all channels
8774 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8775 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8776 check_added_monitors!(nodes[0], 2);
8777 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8778 let events = nodes[0].node.get_and_clear_pending_msg_events();
8779 assert_eq!(events.len(), 2);
8781 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8782 assert_eq!(msg.contents.flags & 2, 2);
8784 _ => panic!("Unexpected event"),
8787 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8788 assert_eq!(msg.contents.flags & 2, 2);
8790 _ => panic!("Unexpected event"),
8792 // Note that at this point users of a standard PeerHandler will end up calling
8793 // peer_disconnected with no_connection_possible set to false, duplicating the
8794 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8795 // users with their own peer handling logic. We duplicate the call here, however.
8796 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8797 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8799 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8800 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8801 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8805 fn test_invalid_funding_tx() {
8806 // Test that we properly handle invalid funding transactions sent to us from a peer.
8808 // Previously, all other major lightning implementations had failed to properly sanitize
8809 // funding transactions from their counterparties, leading to a multi-implementation critical
8810 // security vulnerability (though we always sanitized properly, we've previously had
8811 // un-released crashes in the sanitization process).
8813 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8814 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8815 // gave up on it. We test this here by generating such a transaction.
8816 let chanmon_cfgs = create_chanmon_cfgs(2);
8817 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8818 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8819 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8821 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8822 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
8823 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8825 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8827 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8828 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8829 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8831 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8832 let wit_program_script: Script = wit_program.into();
8833 for output in tx.output.iter_mut() {
8834 // Make the confirmed funding transaction have a bogus script_pubkey
8835 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8838 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8839 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()));
8840 check_added_monitors!(nodes[1], 1);
8842 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()));
8843 check_added_monitors!(nodes[0], 1);
8845 let events_1 = nodes[0].node.get_and_clear_pending_events();
8846 assert_eq!(events_1.len(), 0);
8848 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8849 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8850 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8852 let expected_err = "funding tx had wrong script/value or output index";
8853 confirm_transaction_at(&nodes[1], &tx, 1);
8854 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8855 check_added_monitors!(nodes[1], 1);
8856 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8857 assert_eq!(events_2.len(), 1);
8858 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8859 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8860 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8861 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8862 } else { panic!(); }
8863 } else { panic!(); }
8864 assert_eq!(nodes[1].node.list_channels().len(), 0);
8866 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8867 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8868 // as its not 32 bytes long.
8869 let mut spend_tx = Transaction {
8870 version: 2i32, lock_time: PackedLockTime::ZERO,
8871 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8872 previous_output: BitcoinOutPoint {
8876 script_sig: Script::new(),
8877 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8878 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8880 output: vec![TxOut {
8882 script_pubkey: Script::new(),
8885 check_spends!(spend_tx, tx);
8886 mine_transaction(&nodes[1], &spend_tx);
8889 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8890 // In the first version of the chain::Confirm interface, after a refactor was made to not
8891 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8892 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8893 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8894 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8895 // spending transaction until height N+1 (or greater). This was due to the way
8896 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8897 // spending transaction at the height the input transaction was confirmed at, not whether we
8898 // should broadcast a spending transaction at the current height.
8899 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8900 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8901 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8902 // until we learned about an additional block.
8904 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8905 // aren't broadcasting transactions too early (ie not broadcasting them at all).
8906 let chanmon_cfgs = create_chanmon_cfgs(3);
8907 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8908 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8909 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8910 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8912 create_announced_chan_between_nodes(&nodes, 0, 1);
8913 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
8914 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8915 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8916 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8918 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8919 check_closed_broadcast!(nodes[1], true);
8920 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8921 check_added_monitors!(nodes[1], 1);
8922 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8923 assert_eq!(node_txn.len(), 1);
8925 let conf_height = nodes[1].best_block_info().1;
8926 if !test_height_before_timelock {
8927 connect_blocks(&nodes[1], 24 * 6);
8929 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8930 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8931 if test_height_before_timelock {
8932 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8933 // generate any events or broadcast any transactions
8934 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8935 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8937 // We should broadcast an HTLC transaction spending our funding transaction first
8938 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8939 assert_eq!(spending_txn.len(), 2);
8940 assert_eq!(spending_txn[0], node_txn[0]);
8941 check_spends!(spending_txn[1], node_txn[0]);
8942 // We should also generate a SpendableOutputs event with the to_self output (as its
8944 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8945 assert_eq!(descriptor_spend_txn.len(), 1);
8947 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8948 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8949 // additional block built on top of the current chain.
8950 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8951 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8952 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 }]);
8953 check_added_monitors!(nodes[1], 1);
8955 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8956 assert!(updates.update_add_htlcs.is_empty());
8957 assert!(updates.update_fulfill_htlcs.is_empty());
8958 assert_eq!(updates.update_fail_htlcs.len(), 1);
8959 assert!(updates.update_fail_malformed_htlcs.is_empty());
8960 assert!(updates.update_fee.is_none());
8961 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8962 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8963 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
8968 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
8969 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
8970 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
8973 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
8974 let chanmon_cfgs = create_chanmon_cfgs(2);
8975 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8976 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8977 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8979 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8981 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
8982 .with_features(nodes[1].node.invoice_features());
8983 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
8985 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
8988 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8989 check_added_monitors!(nodes[0], 1);
8990 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8991 assert_eq!(events.len(), 1);
8992 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8993 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8994 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8996 expect_pending_htlcs_forwardable!(nodes[1]);
8997 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9000 // Note that we use a different PaymentId here to allow us to duplicativly pay
9001 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9002 check_added_monitors!(nodes[0], 1);
9003 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9004 assert_eq!(events.len(), 1);
9005 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9006 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9007 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9008 // At this point, nodes[1] would notice it has too much value for the payment. It will
9009 // assume the second is a privacy attack (no longer particularly relevant
9010 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9011 // the first HTLC delivered above.
9014 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9015 nodes[1].node.process_pending_htlc_forwards();
9017 if test_for_second_fail_panic {
9018 // Now we go fail back the first HTLC from the user end.
9019 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9021 let expected_destinations = vec![
9022 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9023 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9025 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9026 nodes[1].node.process_pending_htlc_forwards();
9028 check_added_monitors!(nodes[1], 1);
9029 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9030 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9032 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9033 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9034 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9036 let failure_events = nodes[0].node.get_and_clear_pending_events();
9037 assert_eq!(failure_events.len(), 2);
9038 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9039 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9041 // Let the second HTLC fail and claim the first
9042 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9043 nodes[1].node.process_pending_htlc_forwards();
9045 check_added_monitors!(nodes[1], 1);
9046 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9047 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9048 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9050 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9052 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9057 fn test_dup_htlc_second_fail_panic() {
9058 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9059 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9060 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9061 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9062 do_test_dup_htlc_second_rejected(true);
9066 fn test_dup_htlc_second_rejected() {
9067 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9068 // simply reject the second HTLC but are still able to claim the first HTLC.
9069 do_test_dup_htlc_second_rejected(false);
9073 fn test_inconsistent_mpp_params() {
9074 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9075 // such HTLC and allow the second to stay.
9076 let chanmon_cfgs = create_chanmon_cfgs(4);
9077 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9078 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9079 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9081 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9082 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9083 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9084 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9086 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9087 .with_features(nodes[3].node.invoice_features());
9088 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9089 assert_eq!(route.paths.len(), 2);
9090 route.paths.sort_by(|path_a, _| {
9091 // Sort the path so that the path through nodes[1] comes first
9092 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9093 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9095 let payment_params_opt = Some(payment_params);
9097 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9099 let cur_height = nodes[0].best_block_info().1;
9100 let payment_id = PaymentId([42; 32]);
9102 let session_privs = {
9103 // We create a fake route here so that we start with three pending HTLCs, which we'll
9104 // ultimately have, just not right away.
9105 let mut dup_route = route.clone();
9106 dup_route.paths.push(route.paths[1].clone());
9107 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9110 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();
9111 check_added_monitors!(nodes[0], 1);
9113 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9114 assert_eq!(events.len(), 1);
9115 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9117 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9120 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();
9121 check_added_monitors!(nodes[0], 1);
9123 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9124 assert_eq!(events.len(), 1);
9125 let payment_event = SendEvent::from_event(events.pop().unwrap());
9127 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9128 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9130 expect_pending_htlcs_forwardable!(nodes[2]);
9131 check_added_monitors!(nodes[2], 1);
9133 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9134 assert_eq!(events.len(), 1);
9135 let payment_event = SendEvent::from_event(events.pop().unwrap());
9137 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9138 check_added_monitors!(nodes[3], 0);
9139 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9141 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9142 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9143 // post-payment_secrets) and fail back the new HTLC.
9145 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9146 nodes[3].node.process_pending_htlc_forwards();
9147 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9148 nodes[3].node.process_pending_htlc_forwards();
9150 check_added_monitors!(nodes[3], 1);
9152 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9153 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9154 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9156 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 }]);
9157 check_added_monitors!(nodes[2], 1);
9159 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9160 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9161 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9163 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9165 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();
9166 check_added_monitors!(nodes[0], 1);
9168 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9169 assert_eq!(events.len(), 1);
9170 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9172 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9176 fn test_keysend_payments_to_public_node() {
9177 let chanmon_cfgs = create_chanmon_cfgs(2);
9178 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9179 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9180 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9182 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9183 let network_graph = nodes[0].network_graph.clone();
9184 let payer_pubkey = nodes[0].node.get_our_node_id();
9185 let payee_pubkey = nodes[1].node.get_our_node_id();
9186 let route_params = RouteParameters {
9187 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9188 final_value_msat: 10000,
9189 final_cltv_expiry_delta: 40,
9191 let scorer = test_utils::TestScorer::with_penalty(0);
9192 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9193 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9195 let test_preimage = PaymentPreimage([42; 32]);
9196 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9197 check_added_monitors!(nodes[0], 1);
9198 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9199 assert_eq!(events.len(), 1);
9200 let event = events.pop().unwrap();
9201 let path = vec![&nodes[1]];
9202 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9203 claim_payment(&nodes[0], &path, test_preimage);
9207 fn test_keysend_payments_to_private_node() {
9208 let chanmon_cfgs = create_chanmon_cfgs(2);
9209 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9210 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9211 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9213 let payer_pubkey = nodes[0].node.get_our_node_id();
9214 let payee_pubkey = nodes[1].node.get_our_node_id();
9215 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
9216 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
9218 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9219 let route_params = RouteParameters {
9220 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9221 final_value_msat: 10000,
9222 final_cltv_expiry_delta: 40,
9224 let network_graph = nodes[0].network_graph.clone();
9225 let first_hops = nodes[0].node.list_usable_channels();
9226 let scorer = test_utils::TestScorer::with_penalty(0);
9227 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9228 let route = find_route(
9229 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9230 nodes[0].logger, &scorer, &random_seed_bytes
9233 let test_preimage = PaymentPreimage([42; 32]);
9234 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9235 check_added_monitors!(nodes[0], 1);
9236 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9237 assert_eq!(events.len(), 1);
9238 let event = events.pop().unwrap();
9239 let path = vec![&nodes[1]];
9240 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9241 claim_payment(&nodes[0], &path, test_preimage);
9245 fn test_double_partial_claim() {
9246 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9247 // time out, the sender resends only some of the MPP parts, then the user processes the
9248 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9250 let chanmon_cfgs = create_chanmon_cfgs(4);
9251 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9252 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9253 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9255 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9256 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9257 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9258 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9260 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9261 assert_eq!(route.paths.len(), 2);
9262 route.paths.sort_by(|path_a, _| {
9263 // Sort the path so that the path through nodes[1] comes first
9264 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9265 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9268 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9269 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9270 // amount of time to respond to.
9272 // Connect some blocks to time out the payment
9273 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9274 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9276 let failed_destinations = vec![
9277 HTLCDestination::FailedPayment { payment_hash },
9278 HTLCDestination::FailedPayment { payment_hash },
9280 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9282 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9284 // nodes[1] now retries one of the two paths...
9285 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9286 check_added_monitors!(nodes[0], 2);
9288 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9289 assert_eq!(events.len(), 2);
9290 let (node_1_msgs, _events) = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &events);
9291 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9293 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9294 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9295 nodes[3].node.claim_funds(payment_preimage);
9296 check_added_monitors!(nodes[3], 0);
9297 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9300 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9301 #[derive(Clone, Copy, PartialEq)]
9302 enum ExposureEvent {
9303 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9305 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9307 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9308 AtUpdateFeeOutbound,
9311 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9312 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9315 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9316 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9317 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9318 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9319 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9320 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9321 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9322 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9324 let chanmon_cfgs = create_chanmon_cfgs(2);
9325 let mut config = test_default_channel_config();
9326 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9327 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9328 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9329 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9331 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9332 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9333 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9334 open_channel.max_accepted_htlcs = 60;
9336 open_channel.dust_limit_satoshis = 546;
9338 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9339 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9340 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9342 let opt_anchors = false;
9344 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9347 let mut node_0_per_peer_lock;
9348 let mut node_0_peer_state_lock;
9349 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9350 chan.holder_dust_limit_satoshis = 546;
9353 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9354 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()));
9355 check_added_monitors!(nodes[1], 1);
9357 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()));
9358 check_added_monitors!(nodes[0], 1);
9360 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9361 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9362 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9364 let dust_buffer_feerate = {
9365 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9366 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9367 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9368 chan.get_dust_buffer_feerate(None) as u64
9370 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;
9371 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9373 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;
9374 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9376 let dust_htlc_on_counterparty_tx: u64 = 25;
9377 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9380 if dust_outbound_balance {
9381 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9382 // Outbound dust balance: 4372 sats
9383 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9384 for i in 0..dust_outbound_htlc_on_holder_tx {
9385 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9386 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); }
9389 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9390 // Inbound dust balance: 4372 sats
9391 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9392 for _ in 0..dust_inbound_htlc_on_holder_tx {
9393 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9397 if dust_outbound_balance {
9398 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9399 // Outbound dust balance: 5000 sats
9400 for i in 0..dust_htlc_on_counterparty_tx {
9401 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9402 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); }
9405 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9406 // Inbound dust balance: 5000 sats
9407 for _ in 0..dust_htlc_on_counterparty_tx {
9408 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9413 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9414 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9415 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 });
9416 let mut config = UserConfig::default();
9417 // With default dust exposure: 5000 sats
9419 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9420 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9421 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)));
9423 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)));
9425 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9426 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 });
9427 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9428 check_added_monitors!(nodes[1], 1);
9429 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9430 assert_eq!(events.len(), 1);
9431 let payment_event = SendEvent::from_event(events.remove(0));
9432 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9433 // With default dust exposure: 5000 sats
9435 // Outbound dust balance: 6399 sats
9436 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9437 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9438 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);
9440 // Outbound dust balance: 5200 sats
9441 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);
9443 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9444 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9445 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", ); }
9447 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9448 *feerate_lock = *feerate_lock * 10;
9450 nodes[0].node.timer_tick_occurred();
9451 check_added_monitors!(nodes[0], 1);
9452 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);
9455 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9456 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9457 added_monitors.clear();
9461 fn test_max_dust_htlc_exposure() {
9462 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9463 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9464 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9465 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9466 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9467 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9468 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9469 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9470 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9471 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9472 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9473 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9477 fn test_non_final_funding_tx() {
9478 let chanmon_cfgs = create_chanmon_cfgs(2);
9479 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9480 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9481 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9483 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9484 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9485 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9486 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9487 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9489 let best_height = nodes[0].node.best_block.read().unwrap().height();
9491 let chan_id = *nodes[0].network_chan_count.borrow();
9492 let events = nodes[0].node.get_and_clear_pending_events();
9493 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9494 assert_eq!(events.len(), 1);
9495 let mut tx = match events[0] {
9496 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9497 // Timelock the transaction _beyond_ the best client height + 2.
9498 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9499 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9502 _ => panic!("Unexpected event"),
9504 // Transaction should fail as it's evaluated as non-final for propagation.
9505 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9506 Err(APIError::APIMisuseError { err }) => {
9507 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9512 // However, transaction should be accepted if it's in a +2 headroom from best block.
9513 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9514 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9515 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9519 fn accept_busted_but_better_fee() {
9520 // If a peer sends us a fee update that is too low, but higher than our previous channel
9521 // feerate, we should accept it. In the future we may want to consider closing the channel
9522 // later, but for now we only accept the update.
9523 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9526 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9528 create_chan_between_nodes(&nodes[0], &nodes[1]);
9530 // Set nodes[1] to expect 5,000 sat/kW.
9532 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9533 *feerate_lock = 5000;
9536 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9538 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9539 *feerate_lock = 1000;
9541 nodes[0].node.timer_tick_occurred();
9542 check_added_monitors!(nodes[0], 1);
9544 let events = nodes[0].node.get_and_clear_pending_msg_events();
9545 assert_eq!(events.len(), 1);
9547 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9548 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9549 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9551 _ => panic!("Unexpected event"),
9554 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9557 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9558 *feerate_lock = 2000;
9560 nodes[0].node.timer_tick_occurred();
9561 check_added_monitors!(nodes[0], 1);
9563 let events = nodes[0].node.get_and_clear_pending_msg_events();
9564 assert_eq!(events.len(), 1);
9566 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9567 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9568 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9570 _ => panic!("Unexpected event"),
9573 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9576 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9577 *feerate_lock = 1000;
9579 nodes[0].node.timer_tick_occurred();
9580 check_added_monitors!(nodes[0], 1);
9582 let events = nodes[0].node.get_and_clear_pending_msg_events();
9583 assert_eq!(events.len(), 1);
9585 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9586 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9587 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9588 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9589 check_closed_broadcast!(nodes[1], true);
9590 check_added_monitors!(nodes[1], 1);
9592 _ => panic!("Unexpected event"),
9596 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9597 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9600 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9601 let min_final_cltv_expiry_delta = 120;
9602 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9603 min_final_cltv_expiry_delta - 2 };
9604 let recv_value = 100_000;
9606 create_chan_between_nodes(&nodes[0], &nodes[1]);
9608 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id());
9609 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9610 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9611 Some(recv_value), Some(min_final_cltv_expiry_delta));
9612 (payment_hash, payment_preimage, payment_secret)
9614 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9615 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9617 let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9618 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9619 check_added_monitors!(nodes[0], 1);
9620 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9621 assert_eq!(events.len(), 1);
9622 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9623 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9624 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9625 expect_pending_htlcs_forwardable!(nodes[1]);
9628 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9629 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9631 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9633 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9635 check_added_monitors!(nodes[1], 1);
9637 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9638 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9639 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9641 expect_payment_failed!(nodes[0], payment_hash, true);
9646 fn test_payment_with_custom_min_cltv_expiry_delta() {
9647 do_payment_with_custom_min_final_cltv_expiry(false, false);
9648 do_payment_with_custom_min_final_cltv_expiry(false, true);
9649 do_payment_with_custom_min_final_cltv_expiry(true, false);
9650 do_payment_with_custom_min_final_cltv_expiry(true, true);