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::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::chain::keysinterface::{BaseSign, KeysInterface};
21 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
23 use crate::ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS};
24 use crate::ln::channel::{Channel, ChannelError};
25 use crate::ln::{chan_utils, onion_utils};
26 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
28 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use crate::ln::features::{ChannelFeatures, NodeFeatures};
31 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use crate::util::enforcing_trait_impls::EnforcingSigner;
33 use crate::util::{byte_utils, test_utils};
34 use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::config::UserConfig;
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &message_mutator(open_channel_message.clone()));
91 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92 assert_eq!(msg_events.len(), 1);
93 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96 &ErrorAction::SendErrorMessage { .. } => {
97 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
99 _ => panic!("unexpected event!"),
101 } else { assert!(false); }
104 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106 // Test all mutations that would make the channel open message insane
107 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_funding_exceeds_no_wumbo_limit() {
127 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130 let chanmon_cfgs = create_chanmon_cfgs(2);
131 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132 node_cfgs[1].features = channelmanager::provided_init_features().clear_wumbo();
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
179 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
180 chan.holder_selected_channel_reserve_satoshis = 0;
181 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
184 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
185 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
186 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
188 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
189 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
190 if send_from_initiator {
191 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
192 // Note that for outbound channels we have to consider the commitment tx fee and the
193 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
194 // well as an additional HTLC.
195 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
197 send_payment(&nodes[1], &[&nodes[0]], push_amt);
202 fn test_counterparty_no_reserve() {
203 do_test_counterparty_no_reserve(true);
204 do_test_counterparty_no_reserve(false);
208 fn test_async_inbound_update_fee() {
209 let chanmon_cfgs = create_chanmon_cfgs(2);
210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
212 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
213 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
216 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
220 // send (1) commitment_signed -.
221 // <- update_add_htlc/commitment_signed
222 // send (2) RAA (awaiting remote revoke) -.
223 // (1) commitment_signed is delivered ->
224 // .- send (3) RAA (awaiting remote revoke)
225 // (2) RAA is delivered ->
226 // .- send (4) commitment_signed
227 // <- (3) RAA is delivered
228 // send (5) commitment_signed -.
229 // <- (4) commitment_signed is delivered
231 // (5) commitment_signed is delivered ->
233 // (6) RAA is delivered ->
235 // First nodes[0] generates an update_fee
237 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
240 nodes[0].node.timer_tick_occurred();
241 check_added_monitors!(nodes[0], 1);
243 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
244 assert_eq!(events_0.len(), 1);
245 let (update_msg, commitment_signed) = match events_0[0] { // (1)
246 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
247 (update_fee.as_ref(), commitment_signed)
249 _ => panic!("Unexpected event"),
252 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
254 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
255 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
256 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
257 check_added_monitors!(nodes[1], 1);
259 let payment_event = {
260 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
261 assert_eq!(events_1.len(), 1);
262 SendEvent::from_event(events_1.remove(0))
264 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
265 assert_eq!(payment_event.msgs.len(), 1);
267 // ...now when the messages get delivered everyone should be happy
268 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
269 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
270 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
272 check_added_monitors!(nodes[0], 1);
274 // deliver(1), generate (3):
275 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
276 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
277 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
278 check_added_monitors!(nodes[1], 1);
280 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
281 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
282 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
283 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
284 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
285 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
286 assert!(bs_update.update_fee.is_none()); // (4)
287 check_added_monitors!(nodes[1], 1);
289 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
290 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
291 assert!(as_update.update_add_htlcs.is_empty()); // (5)
292 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
293 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
294 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
295 assert!(as_update.update_fee.is_none()); // (5)
296 check_added_monitors!(nodes[0], 1);
298 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
299 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
300 // only (6) so get_event_msg's assert(len == 1) passes
301 check_added_monitors!(nodes[0], 1);
303 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
304 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
305 check_added_monitors!(nodes[1], 1);
307 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
308 check_added_monitors!(nodes[0], 1);
310 let events_2 = nodes[0].node.get_and_clear_pending_events();
311 assert_eq!(events_2.len(), 1);
313 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
314 _ => panic!("Unexpected event"),
317 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
318 check_added_monitors!(nodes[1], 1);
322 fn test_update_fee_unordered_raa() {
323 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
324 // crash in an earlier version of the update_fee patch)
325 let chanmon_cfgs = create_chanmon_cfgs(2);
326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
328 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
329 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
332 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
334 // First nodes[0] generates an update_fee
336 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
339 nodes[0].node.timer_tick_occurred();
340 check_added_monitors!(nodes[0], 1);
342 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
343 assert_eq!(events_0.len(), 1);
344 let update_msg = match events_0[0] { // (1)
345 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
348 _ => panic!("Unexpected event"),
351 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
353 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
354 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
355 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
356 check_added_monitors!(nodes[1], 1);
358 let payment_event = {
359 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
360 assert_eq!(events_1.len(), 1);
361 SendEvent::from_event(events_1.remove(0))
363 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
364 assert_eq!(payment_event.msgs.len(), 1);
366 // ...now when the messages get delivered everyone should be happy
367 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
368 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
369 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
371 check_added_monitors!(nodes[0], 1);
373 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
374 check_added_monitors!(nodes[1], 1);
376 // We can't continue, sadly, because our (1) now has a bogus signature
380 fn test_multi_flight_update_fee() {
381 let chanmon_cfgs = create_chanmon_cfgs(2);
382 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
383 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
384 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
385 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
388 // update_fee/commitment_signed ->
389 // .- send (1) RAA and (2) commitment_signed
390 // update_fee (never committed) ->
392 // We have to manually generate the above update_fee, it is allowed by the protocol but we
393 // don't track which updates correspond to which revoke_and_ack responses so we're in
394 // AwaitingRAA mode and will not generate the update_fee yet.
395 // <- (1) RAA delivered
396 // (3) is generated and send (4) CS -.
397 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
398 // know the per_commitment_point to use for it.
399 // <- (2) commitment_signed delivered
401 // B should send no response here
402 // (4) commitment_signed delivered ->
403 // <- RAA/commitment_signed delivered
406 // First nodes[0] generates an update_fee
409 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
410 initial_feerate = *feerate_lock;
411 *feerate_lock = initial_feerate + 20;
413 nodes[0].node.timer_tick_occurred();
414 check_added_monitors!(nodes[0], 1);
416 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
417 assert_eq!(events_0.len(), 1);
418 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
419 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
420 (update_fee.as_ref().unwrap(), commitment_signed)
422 _ => panic!("Unexpected event"),
425 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
426 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
427 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
428 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
429 check_added_monitors!(nodes[1], 1);
431 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
434 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
435 *feerate_lock = initial_feerate + 40;
437 nodes[0].node.timer_tick_occurred();
438 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
439 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
441 // Create the (3) update_fee message that nodes[0] will generate before it does...
442 let mut update_msg_2 = msgs::UpdateFee {
443 channel_id: update_msg_1.channel_id.clone(),
444 feerate_per_kw: (initial_feerate + 30) as u32,
447 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
449 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
451 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
453 // Deliver (1), generating (3) and (4)
454 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
455 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
456 check_added_monitors!(nodes[0], 1);
457 assert!(as_second_update.update_add_htlcs.is_empty());
458 assert!(as_second_update.update_fulfill_htlcs.is_empty());
459 assert!(as_second_update.update_fail_htlcs.is_empty());
460 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
461 // Check that the update_fee newly generated matches what we delivered:
462 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
463 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
465 // Deliver (2) commitment_signed
466 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
467 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
468 check_added_monitors!(nodes[0], 1);
469 // No commitment_signed so get_event_msg's assert(len == 1) passes
471 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
472 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
473 check_added_monitors!(nodes[1], 1);
476 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
477 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
478 check_added_monitors!(nodes[1], 1);
480 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
481 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
482 check_added_monitors!(nodes[0], 1);
484 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
485 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
486 // No commitment_signed so get_event_msg's assert(len == 1) passes
487 check_added_monitors!(nodes[0], 1);
489 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
490 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
491 check_added_monitors!(nodes[1], 1);
494 fn do_test_sanity_on_in_flight_opens(steps: u8) {
495 // Previously, we had issues deserializing channels when we hadn't connected the first block
496 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
497 // serialization round-trips and simply do steps towards opening a channel and then drop the
500 let chanmon_cfgs = create_chanmon_cfgs(2);
501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
503 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
505 if steps & 0b1000_0000 != 0{
507 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
510 connect_block(&nodes[0], &block);
511 connect_block(&nodes[1], &block);
514 if steps & 0x0f == 0 { return; }
515 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
516 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
518 if steps & 0x0f == 1 { return; }
519 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
520 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
522 if steps & 0x0f == 2 { return; }
523 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
525 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
527 if steps & 0x0f == 3 { return; }
528 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
529 check_added_monitors!(nodes[0], 0);
530 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
532 if steps & 0x0f == 4 { return; }
533 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
535 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
536 assert_eq!(added_monitors.len(), 1);
537 assert_eq!(added_monitors[0].0, funding_output);
538 added_monitors.clear();
540 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
542 if steps & 0x0f == 5 { return; }
543 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
545 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
546 assert_eq!(added_monitors.len(), 1);
547 assert_eq!(added_monitors[0].0, funding_output);
548 added_monitors.clear();
551 let events_4 = nodes[0].node.get_and_clear_pending_events();
552 assert_eq!(events_4.len(), 0);
554 if steps & 0x0f == 6 { return; }
555 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
557 if steps & 0x0f == 7 { return; }
558 confirm_transaction_at(&nodes[0], &tx, 2);
559 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
560 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
561 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
565 fn test_sanity_on_in_flight_opens() {
566 do_test_sanity_on_in_flight_opens(0);
567 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
568 do_test_sanity_on_in_flight_opens(1);
569 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
570 do_test_sanity_on_in_flight_opens(2);
571 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
572 do_test_sanity_on_in_flight_opens(3);
573 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
574 do_test_sanity_on_in_flight_opens(4);
575 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
576 do_test_sanity_on_in_flight_opens(5);
577 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
578 do_test_sanity_on_in_flight_opens(6);
579 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
580 do_test_sanity_on_in_flight_opens(7);
581 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
582 do_test_sanity_on_in_flight_opens(8);
583 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
587 fn test_update_fee_vanilla() {
588 let chanmon_cfgs = create_chanmon_cfgs(2);
589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
591 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
592 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
595 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
598 nodes[0].node.timer_tick_occurred();
599 check_added_monitors!(nodes[0], 1);
601 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
602 assert_eq!(events_0.len(), 1);
603 let (update_msg, commitment_signed) = match events_0[0] {
604 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
605 (update_fee.as_ref(), commitment_signed)
607 _ => panic!("Unexpected event"),
609 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
611 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
612 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
613 check_added_monitors!(nodes[1], 1);
615 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
616 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
617 check_added_monitors!(nodes[0], 1);
619 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
620 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
621 // No commitment_signed so get_event_msg's assert(len == 1) passes
622 check_added_monitors!(nodes[0], 1);
624 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
625 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
626 check_added_monitors!(nodes[1], 1);
630 fn test_update_fee_that_funder_cannot_afford() {
631 let chanmon_cfgs = create_chanmon_cfgs(2);
632 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
633 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
634 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
635 let channel_value = 5000;
637 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
638 let channel_id = chan.2;
639 let secp_ctx = Secp256k1::new();
640 let default_config = UserConfig::default();
641 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
643 let opt_anchors = false;
645 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
646 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
647 // calculate two different feerates here - the expected local limit as well as the expected
649 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
650 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
652 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
653 *feerate_lock = feerate;
655 nodes[0].node.timer_tick_occurred();
656 check_added_monitors!(nodes[0], 1);
657 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
659 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
661 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
663 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
665 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
667 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
668 assert_eq!(commitment_tx.output.len(), 2);
669 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
670 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
671 actual_fee = channel_value - actual_fee;
672 assert_eq!(total_fee, actual_fee);
676 // Increment the feerate by a small constant, accounting for rounding errors
677 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
680 nodes[0].node.timer_tick_occurred();
681 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
682 check_added_monitors!(nodes[0], 0);
684 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
686 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
687 // needed to sign the new commitment tx and (2) sign the new commitment tx.
688 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
689 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
690 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
691 let chan_signer = local_chan.get_signer();
692 let pubkeys = chan_signer.pubkeys();
693 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
694 pubkeys.funding_pubkey)
696 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
697 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
698 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
699 let chan_signer = remote_chan.get_signer();
700 let pubkeys = chan_signer.pubkeys();
701 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
702 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
703 pubkeys.funding_pubkey)
706 // Assemble the set of keys we can use for signatures for our commitment_signed message.
707 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
708 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
711 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
712 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
713 let local_chan_signer = local_chan.get_signer();
714 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
715 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
716 INITIAL_COMMITMENT_NUMBER - 1,
718 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
719 opt_anchors, local_funding, remote_funding,
720 commit_tx_keys.clone(),
721 non_buffer_feerate + 4,
723 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
725 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
728 let commit_signed_msg = msgs::CommitmentSigned {
731 htlc_signatures: res.1
734 let update_fee = msgs::UpdateFee {
736 feerate_per_kw: non_buffer_feerate + 4,
739 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
741 //While producing the commitment_signed response after handling a received update_fee request the
742 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
743 //Should produce and error.
744 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
745 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
746 check_added_monitors!(nodes[1], 1);
747 check_closed_broadcast!(nodes[1], true);
748 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
752 fn test_update_fee_with_fundee_update_add_htlc() {
753 let chanmon_cfgs = create_chanmon_cfgs(2);
754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
756 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
757 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
760 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
763 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
766 nodes[0].node.timer_tick_occurred();
767 check_added_monitors!(nodes[0], 1);
769 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
770 assert_eq!(events_0.len(), 1);
771 let (update_msg, commitment_signed) = match events_0[0] {
772 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
773 (update_fee.as_ref(), commitment_signed)
775 _ => panic!("Unexpected event"),
777 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
778 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
779 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
780 check_added_monitors!(nodes[1], 1);
782 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
784 // nothing happens since node[1] is in AwaitingRemoteRevoke
785 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
787 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
788 assert_eq!(added_monitors.len(), 0);
789 added_monitors.clear();
791 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
792 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
793 // node[1] has nothing to do
795 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797 check_added_monitors!(nodes[0], 1);
799 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
800 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
801 // No commitment_signed so get_event_msg's assert(len == 1) passes
802 check_added_monitors!(nodes[0], 1);
803 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
804 check_added_monitors!(nodes[1], 1);
805 // AwaitingRemoteRevoke ends here
807 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
808 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
809 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
810 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
811 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
812 assert_eq!(commitment_update.update_fee.is_none(), true);
814 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
815 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
816 check_added_monitors!(nodes[0], 1);
817 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
819 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
820 check_added_monitors!(nodes[1], 1);
821 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
823 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
824 check_added_monitors!(nodes[1], 1);
825 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
826 // No commitment_signed so get_event_msg's assert(len == 1) passes
828 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
829 check_added_monitors!(nodes[0], 1);
830 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
832 expect_pending_htlcs_forwardable!(nodes[0]);
834 let events = nodes[0].node.get_and_clear_pending_events();
835 assert_eq!(events.len(), 1);
837 Event::PaymentReceived { .. } => { },
838 _ => panic!("Unexpected event"),
841 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
843 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
844 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
845 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
846 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
847 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
851 fn test_update_fee() {
852 let chanmon_cfgs = create_chanmon_cfgs(2);
853 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
854 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
855 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
856 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
857 let channel_id = chan.2;
860 // (1) update_fee/commitment_signed ->
861 // <- (2) revoke_and_ack
862 // .- send (3) commitment_signed
863 // (4) update_fee/commitment_signed ->
864 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
865 // <- (3) commitment_signed delivered
866 // send (6) revoke_and_ack -.
867 // <- (5) deliver revoke_and_ack
868 // (6) deliver revoke_and_ack ->
869 // .- send (7) commitment_signed in response to (4)
870 // <- (7) deliver commitment_signed
873 // Create and deliver (1)...
876 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
877 feerate = *feerate_lock;
878 *feerate_lock = feerate + 20;
880 nodes[0].node.timer_tick_occurred();
881 check_added_monitors!(nodes[0], 1);
883 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
884 assert_eq!(events_0.len(), 1);
885 let (update_msg, commitment_signed) = match events_0[0] {
886 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
887 (update_fee.as_ref(), commitment_signed)
889 _ => panic!("Unexpected event"),
891 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
893 // Generate (2) and (3):
894 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
895 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
896 check_added_monitors!(nodes[1], 1);
899 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
900 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
901 check_added_monitors!(nodes[0], 1);
903 // Create and deliver (4)...
905 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
906 *feerate_lock = feerate + 30;
908 nodes[0].node.timer_tick_occurred();
909 check_added_monitors!(nodes[0], 1);
910 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
911 assert_eq!(events_0.len(), 1);
912 let (update_msg, commitment_signed) = match events_0[0] {
913 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
914 (update_fee.as_ref(), commitment_signed)
916 _ => panic!("Unexpected event"),
919 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
920 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
921 check_added_monitors!(nodes[1], 1);
923 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
924 // No commitment_signed so get_event_msg's assert(len == 1) passes
926 // Handle (3), creating (6):
927 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
928 check_added_monitors!(nodes[0], 1);
929 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
930 // No commitment_signed so get_event_msg's assert(len == 1) passes
933 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
934 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
935 check_added_monitors!(nodes[0], 1);
937 // Deliver (6), creating (7):
938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
939 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
940 assert!(commitment_update.update_add_htlcs.is_empty());
941 assert!(commitment_update.update_fulfill_htlcs.is_empty());
942 assert!(commitment_update.update_fail_htlcs.is_empty());
943 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
944 assert!(commitment_update.update_fee.is_none());
945 check_added_monitors!(nodes[1], 1);
948 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
949 check_added_monitors!(nodes[0], 1);
950 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
951 // No commitment_signed so get_event_msg's assert(len == 1) passes
953 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
954 check_added_monitors!(nodes[1], 1);
955 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
957 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
958 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
959 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
960 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
961 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
965 fn fake_network_test() {
966 // Simple test which builds a network of ChannelManagers, connects them to each other, and
967 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
968 let chanmon_cfgs = create_chanmon_cfgs(4);
969 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
970 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
971 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
973 // Create some initial channels
974 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
975 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
976 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
978 // Rebalance the network a bit by relaying one payment through all the channels...
979 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
980 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
981 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
982 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
984 // Send some more payments
985 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
986 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
987 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
989 // Test failure packets
990 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
991 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
993 // Add a new channel that skips 3
994 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
996 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
997 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
998 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
999 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1000 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1001 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1002 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1004 // Do some rebalance loop payments, simultaneously
1005 let mut hops = Vec::with_capacity(3);
1006 hops.push(RouteHop {
1007 pubkey: nodes[2].node.get_our_node_id(),
1008 node_features: NodeFeatures::empty(),
1009 short_channel_id: chan_2.0.contents.short_channel_id,
1010 channel_features: ChannelFeatures::empty(),
1012 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1014 hops.push(RouteHop {
1015 pubkey: nodes[3].node.get_our_node_id(),
1016 node_features: NodeFeatures::empty(),
1017 short_channel_id: chan_3.0.contents.short_channel_id,
1018 channel_features: ChannelFeatures::empty(),
1020 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1022 hops.push(RouteHop {
1023 pubkey: nodes[1].node.get_our_node_id(),
1024 node_features: channelmanager::provided_node_features(),
1025 short_channel_id: chan_4.0.contents.short_channel_id,
1026 channel_features: channelmanager::provided_channel_features(),
1028 cltv_expiry_delta: TEST_FINAL_CLTV,
1030 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1031 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1032 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1034 let mut hops = Vec::with_capacity(3);
1035 hops.push(RouteHop {
1036 pubkey: nodes[3].node.get_our_node_id(),
1037 node_features: NodeFeatures::empty(),
1038 short_channel_id: chan_4.0.contents.short_channel_id,
1039 channel_features: ChannelFeatures::empty(),
1041 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1043 hops.push(RouteHop {
1044 pubkey: nodes[2].node.get_our_node_id(),
1045 node_features: NodeFeatures::empty(),
1046 short_channel_id: chan_3.0.contents.short_channel_id,
1047 channel_features: ChannelFeatures::empty(),
1049 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1051 hops.push(RouteHop {
1052 pubkey: nodes[1].node.get_our_node_id(),
1053 node_features: channelmanager::provided_node_features(),
1054 short_channel_id: chan_2.0.contents.short_channel_id,
1055 channel_features: channelmanager::provided_channel_features(),
1057 cltv_expiry_delta: TEST_FINAL_CLTV,
1059 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1060 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1061 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1063 // Claim the rebalances...
1064 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1065 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1067 // Close down the channels...
1068 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1069 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1070 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1072 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1073 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1074 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1075 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1076 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1077 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1078 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1079 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1083 fn holding_cell_htlc_counting() {
1084 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1085 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1086 // commitment dance rounds.
1087 let chanmon_cfgs = create_chanmon_cfgs(3);
1088 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1089 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1090 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1091 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1092 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1094 let mut payments = Vec::new();
1095 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1096 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1097 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1098 payments.push((payment_preimage, payment_hash));
1100 check_added_monitors!(nodes[1], 1);
1102 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1103 assert_eq!(events.len(), 1);
1104 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1105 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1107 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1108 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1110 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1112 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1113 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1114 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1115 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1118 // This should also be true if we try to forward a payment.
1119 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1121 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1122 check_added_monitors!(nodes[0], 1);
1125 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1126 assert_eq!(events.len(), 1);
1127 let payment_event = SendEvent::from_event(events.pop().unwrap());
1128 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1130 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1131 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1132 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1133 // fails), the second will process the resulting failure and fail the HTLC backward.
1134 expect_pending_htlcs_forwardable!(nodes[1]);
1135 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1136 check_added_monitors!(nodes[1], 1);
1138 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1139 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1140 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1142 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1144 // Now forward all the pending HTLCs and claim them back
1145 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1146 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1147 check_added_monitors!(nodes[2], 1);
1149 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1150 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1151 check_added_monitors!(nodes[1], 1);
1152 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1154 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1155 check_added_monitors!(nodes[1], 1);
1156 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1158 for ref update in as_updates.update_add_htlcs.iter() {
1159 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1162 check_added_monitors!(nodes[2], 1);
1163 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1164 check_added_monitors!(nodes[2], 1);
1165 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168 check_added_monitors!(nodes[1], 1);
1169 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170 check_added_monitors!(nodes[1], 1);
1171 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1173 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1174 check_added_monitors!(nodes[2], 1);
1176 expect_pending_htlcs_forwardable!(nodes[2]);
1178 let events = nodes[2].node.get_and_clear_pending_events();
1179 assert_eq!(events.len(), payments.len());
1180 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1182 &Event::PaymentReceived { ref payment_hash, .. } => {
1183 assert_eq!(*payment_hash, *hash);
1185 _ => panic!("Unexpected event"),
1189 for (preimage, _) in payments.drain(..) {
1190 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1193 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1197 fn duplicate_htlc_test() {
1198 // Test that we accept duplicate payment_hash HTLCs across the network and that
1199 // claiming/failing them are all separate and don't affect each other
1200 let chanmon_cfgs = create_chanmon_cfgs(6);
1201 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1202 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1203 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1205 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1206 create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1207 create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1208 create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1209 create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1210 create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1212 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1214 *nodes[0].network_payment_count.borrow_mut() -= 1;
1215 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1217 *nodes[0].network_payment_count.borrow_mut() -= 1;
1218 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1220 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1221 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1222 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1226 fn test_duplicate_htlc_different_direction_onchain() {
1227 // Test that ChannelMonitor doesn't generate 2 preimage txn
1228 // when we have 2 HTLCs with same preimage that go across a node
1229 // in opposite directions, even with the same payment secret.
1230 let chanmon_cfgs = create_chanmon_cfgs(2);
1231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1233 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1235 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1238 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1240 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1242 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1243 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1244 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1246 // Provide preimage to node 0 by claiming payment
1247 nodes[0].node.claim_funds(payment_preimage);
1248 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1249 check_added_monitors!(nodes[0], 1);
1251 // Broadcast node 1 commitment txn
1252 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1254 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1255 let mut has_both_htlcs = 0; // check htlcs match ones committed
1256 for outp in remote_txn[0].output.iter() {
1257 if outp.value == 800_000 / 1000 {
1258 has_both_htlcs += 1;
1259 } else if outp.value == 900_000 / 1000 {
1260 has_both_htlcs += 1;
1263 assert_eq!(has_both_htlcs, 2);
1265 mine_transaction(&nodes[0], &remote_txn[0]);
1266 check_added_monitors!(nodes[0], 1);
1267 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1268 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1270 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1271 assert_eq!(claim_txn.len(), 5);
1273 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1274 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1275 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1277 check_spends!(claim_txn[3], remote_txn[0]);
1278 check_spends!(claim_txn[4], remote_txn[0]);
1279 let preimage_tx = &claim_txn[0];
1280 let (preimage_bump_tx, timeout_tx) = if claim_txn[3].input[0].previous_output == preimage_tx.input[0].previous_output {
1281 (&claim_txn[3], &claim_txn[4])
1283 (&claim_txn[4], &claim_txn[3])
1286 assert_eq!(preimage_tx.input.len(), 1);
1287 assert_eq!(preimage_bump_tx.input.len(), 1);
1289 assert_eq!(preimage_tx.input.len(), 1);
1290 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1291 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1293 assert_eq!(timeout_tx.input.len(), 1);
1294 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1295 check_spends!(timeout_tx, remote_txn[0]);
1296 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1298 let events = nodes[0].node.get_and_clear_pending_msg_events();
1299 assert_eq!(events.len(), 3);
1302 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1303 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1304 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1305 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1307 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1308 assert!(update_add_htlcs.is_empty());
1309 assert!(update_fail_htlcs.is_empty());
1310 assert_eq!(update_fulfill_htlcs.len(), 1);
1311 assert!(update_fail_malformed_htlcs.is_empty());
1312 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1314 _ => panic!("Unexpected event"),
1320 fn test_basic_channel_reserve() {
1321 let chanmon_cfgs = create_chanmon_cfgs(2);
1322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1324 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1325 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1327 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1328 let channel_reserve = chan_stat.channel_reserve_msat;
1330 // The 2* and +1 are for the fee spike reserve.
1331 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1332 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1333 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1334 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1336 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1338 &APIError::ChannelUnavailable{ref err} =>
1339 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1340 _ => panic!("Unexpected error variant"),
1343 _ => panic!("Unexpected error variant"),
1345 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1346 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1348 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1352 fn test_fee_spike_violation_fails_htlc() {
1353 let chanmon_cfgs = create_chanmon_cfgs(2);
1354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1356 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1357 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1359 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1360 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1361 let secp_ctx = Secp256k1::new();
1362 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1364 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1366 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1367 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1368 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1369 let msg = msgs::UpdateAddHTLC {
1372 amount_msat: htlc_msat,
1373 payment_hash: payment_hash,
1374 cltv_expiry: htlc_cltv,
1375 onion_routing_packet: onion_packet,
1378 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1380 // Now manually create the commitment_signed message corresponding to the update_add
1381 // nodes[0] just sent. In the code for construction of this message, "local" refers
1382 // to the sender of the message, and "remote" refers to the receiver.
1384 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1386 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1388 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1389 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1390 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1391 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1392 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1393 let chan_signer = local_chan.get_signer();
1394 // Make the signer believe we validated another commitment, so we can release the secret
1395 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1397 let pubkeys = chan_signer.pubkeys();
1398 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1399 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1400 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1401 chan_signer.pubkeys().funding_pubkey)
1403 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1404 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1405 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1406 let chan_signer = remote_chan.get_signer();
1407 let pubkeys = chan_signer.pubkeys();
1408 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1409 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1410 chan_signer.pubkeys().funding_pubkey)
1413 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1414 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1415 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1417 // Build the remote commitment transaction so we can sign it, and then later use the
1418 // signature for the commitment_signed message.
1419 let local_chan_balance = 1313;
1421 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1423 amount_msat: 3460001,
1424 cltv_expiry: htlc_cltv,
1426 transaction_output_index: Some(1),
1429 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1432 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1433 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1434 let local_chan_signer = local_chan.get_signer();
1435 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1439 local_chan.opt_anchors(), local_funding, remote_funding,
1440 commit_tx_keys.clone(),
1442 &mut vec![(accepted_htlc_info, ())],
1443 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1445 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1448 let commit_signed_msg = msgs::CommitmentSigned {
1451 htlc_signatures: res.1
1454 // Send the commitment_signed message to the nodes[1].
1455 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1456 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1458 // Send the RAA to nodes[1].
1459 let raa_msg = msgs::RevokeAndACK {
1461 per_commitment_secret: local_secret,
1462 next_per_commitment_point: next_local_point
1464 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1466 let events = nodes[1].node.get_and_clear_pending_msg_events();
1467 assert_eq!(events.len(), 1);
1468 // Make sure the HTLC failed in the way we expect.
1470 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1471 assert_eq!(update_fail_htlcs.len(), 1);
1472 update_fail_htlcs[0].clone()
1474 _ => panic!("Unexpected event"),
1476 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1477 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1479 check_added_monitors!(nodes[1], 2);
1483 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1484 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1485 // Set the fee rate for the channel very high, to the point where the fundee
1486 // sending any above-dust amount would result in a channel reserve violation.
1487 // In this test we check that we would be prevented from sending an HTLC in
1489 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1492 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1493 let default_config = UserConfig::default();
1494 let opt_anchors = false;
1496 let mut push_amt = 100_000_000;
1497 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1499 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1501 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1503 // Sending exactly enough to hit the reserve amount should be accepted
1504 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1505 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1508 // However one more HTLC should be significantly over the reserve amount and fail.
1509 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1510 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1511 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1512 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1513 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1517 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1518 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1519 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1522 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523 let default_config = UserConfig::default();
1524 let opt_anchors = false;
1526 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1527 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1528 // transaction fee with 0 HTLCs (183 sats)).
1529 let mut push_amt = 100_000_000;
1530 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1531 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1532 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1534 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1535 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1536 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1539 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1540 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1541 let secp_ctx = Secp256k1::new();
1542 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1543 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1544 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1545 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1546 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1547 let msg = msgs::UpdateAddHTLC {
1549 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1550 amount_msat: htlc_msat,
1551 payment_hash: payment_hash,
1552 cltv_expiry: htlc_cltv,
1553 onion_routing_packet: onion_packet,
1556 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1557 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1558 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1559 assert_eq!(nodes[0].node.list_channels().len(), 0);
1560 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1561 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1562 check_added_monitors!(nodes[0], 1);
1563 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1567 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1568 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1569 // calculating our commitment transaction fee (this was previously broken).
1570 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1571 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1575 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1576 let default_config = UserConfig::default();
1577 let opt_anchors = false;
1579 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1580 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1581 // transaction fee with 0 HTLCs (183 sats)).
1582 let mut push_amt = 100_000_000;
1583 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1584 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1585 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1587 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1588 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1589 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1590 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1591 // commitment transaction fee.
1592 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1594 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1595 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1596 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1599 // One more than the dust amt should fail, however.
1600 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1601 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1602 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1606 fn test_chan_init_feerate_unaffordability() {
1607 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1608 // channel reserve and feerate requirements.
1609 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1610 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1613 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1614 let default_config = UserConfig::default();
1615 let opt_anchors = false;
1617 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1619 let mut push_amt = 100_000_000;
1620 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1621 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1622 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1624 // During open, we don't have a "counterparty channel reserve" to check against, so that
1625 // requirement only comes into play on the open_channel handling side.
1626 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1627 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1628 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1629 open_channel_msg.push_msat += 1;
1630 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1632 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1633 assert_eq!(msg_events.len(), 1);
1634 match msg_events[0] {
1635 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1636 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1638 _ => panic!("Unexpected event"),
1643 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1644 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1645 // calculating our counterparty's commitment transaction fee (this was previously broken).
1646 let chanmon_cfgs = create_chanmon_cfgs(2);
1647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1649 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1650 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1652 let payment_amt = 46000; // Dust amount
1653 // In the previous code, these first four payments would succeed.
1654 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1655 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1656 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1657 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1659 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1660 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1667 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1668 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1669 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1674 let chanmon_cfgs = create_chanmon_cfgs(3);
1675 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1676 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1677 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1678 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1679 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1682 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1683 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1684 let feerate = get_feerate!(nodes[0], chan.2);
1685 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1687 // Add a 2* and +1 for the fee spike reserve.
1688 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1689 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1690 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1692 // Add a pending HTLC.
1693 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1694 let payment_event_1 = {
1695 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1696 check_added_monitors!(nodes[0], 1);
1698 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1699 assert_eq!(events.len(), 1);
1700 SendEvent::from_event(events.remove(0))
1702 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1704 // Attempt to trigger a channel reserve violation --> payment failure.
1705 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1706 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1707 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1708 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1710 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1711 let secp_ctx = Secp256k1::new();
1712 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1713 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1714 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1715 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1716 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1717 let msg = msgs::UpdateAddHTLC {
1720 amount_msat: htlc_msat + 1,
1721 payment_hash: our_payment_hash_1,
1722 cltv_expiry: htlc_cltv,
1723 onion_routing_packet: onion_packet,
1726 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1727 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1728 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1729 assert_eq!(nodes[1].node.list_channels().len(), 1);
1730 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1731 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1732 check_added_monitors!(nodes[1], 1);
1733 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1737 fn test_inbound_outbound_capacity_is_not_zero() {
1738 let chanmon_cfgs = create_chanmon_cfgs(2);
1739 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1740 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1741 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1742 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1743 let channels0 = node_chanmgrs[0].list_channels();
1744 let channels1 = node_chanmgrs[1].list_channels();
1745 let default_config = UserConfig::default();
1746 assert_eq!(channels0.len(), 1);
1747 assert_eq!(channels1.len(), 1);
1749 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1750 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1751 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1753 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1754 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1757 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1758 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1762 fn test_channel_reserve_holding_cell_htlcs() {
1763 let chanmon_cfgs = create_chanmon_cfgs(3);
1764 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1765 // When this test was written, the default base fee floated based on the HTLC count.
1766 // It is now fixed, so we simply set the fee to the expected value here.
1767 let mut config = test_default_channel_config();
1768 config.channel_config.forwarding_fee_base_msat = 239;
1769 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1770 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1771 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1772 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1774 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1775 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1777 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1778 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1780 macro_rules! expect_forward {
1782 let mut events = $node.node.get_and_clear_pending_msg_events();
1783 assert_eq!(events.len(), 1);
1784 check_added_monitors!($node, 1);
1785 let payment_event = SendEvent::from_event(events.remove(0));
1790 let feemsat = 239; // set above
1791 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1792 let feerate = get_feerate!(nodes[0], chan_1.2);
1793 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1795 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1797 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1799 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1800 .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1801 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1802 route.paths[0].last_mut().unwrap().fee_msat += 1;
1803 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1805 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1806 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1808 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1811 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1812 // nodes[0]'s wealth
1814 let amt_msat = recv_value_0 + total_fee_msat;
1815 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1816 // Also, ensure that each payment has enough to be over the dust limit to
1817 // ensure it'll be included in each commit tx fee calculation.
1818 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1819 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1820 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1824 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1825 .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1826 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1827 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1828 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1830 let (stat01_, stat11_, stat12_, stat22_) = (
1831 get_channel_value_stat!(nodes[0], chan_1.2),
1832 get_channel_value_stat!(nodes[1], chan_1.2),
1833 get_channel_value_stat!(nodes[1], chan_2.2),
1834 get_channel_value_stat!(nodes[2], chan_2.2),
1837 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1838 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1839 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1840 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1841 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1844 // adding pending output.
1845 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1846 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1847 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1848 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1849 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1850 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1851 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1852 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1853 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1855 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1856 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1857 let amt_msat_1 = recv_value_1 + total_fee_msat;
1859 let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1860 let payment_event_1 = {
1861 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1862 check_added_monitors!(nodes[0], 1);
1864 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1865 assert_eq!(events.len(), 1);
1866 SendEvent::from_event(events.remove(0))
1868 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1870 // channel reserve test with htlc pending output > 0
1871 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1873 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1874 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1875 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1876 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1879 // split the rest to test holding cell
1880 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1881 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1882 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1883 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1885 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1886 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1889 // now see if they go through on both sides
1890 let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1891 // but this will stuck in the holding cell
1892 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1893 check_added_monitors!(nodes[0], 0);
1894 let events = nodes[0].node.get_and_clear_pending_events();
1895 assert_eq!(events.len(), 0);
1897 // test with outbound holding cell amount > 0
1899 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1900 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1901 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1902 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1903 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
1906 let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1907 // this will also stuck in the holding cell
1908 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1909 check_added_monitors!(nodes[0], 0);
1910 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1913 // flush the pending htlc
1914 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1915 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1916 check_added_monitors!(nodes[1], 1);
1918 // the pending htlc should be promoted to committed
1919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1920 check_added_monitors!(nodes[0], 1);
1921 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1923 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1924 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1925 // No commitment_signed so get_event_msg's assert(len == 1) passes
1926 check_added_monitors!(nodes[0], 1);
1928 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1929 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1930 check_added_monitors!(nodes[1], 1);
1932 expect_pending_htlcs_forwardable!(nodes[1]);
1934 let ref payment_event_11 = expect_forward!(nodes[1]);
1935 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1936 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1938 expect_pending_htlcs_forwardable!(nodes[2]);
1939 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1941 // flush the htlcs in the holding cell
1942 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1943 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1944 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1945 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1946 expect_pending_htlcs_forwardable!(nodes[1]);
1948 let ref payment_event_3 = expect_forward!(nodes[1]);
1949 assert_eq!(payment_event_3.msgs.len(), 2);
1950 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1951 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1953 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1954 expect_pending_htlcs_forwardable!(nodes[2]);
1956 let events = nodes[2].node.get_and_clear_pending_events();
1957 assert_eq!(events.len(), 2);
1959 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1960 assert_eq!(our_payment_hash_21, *payment_hash);
1961 assert_eq!(recv_value_21, amount_msat);
1963 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1964 assert!(payment_preimage.is_none());
1965 assert_eq!(our_payment_secret_21, *payment_secret);
1967 _ => panic!("expected PaymentPurpose::InvoicePayment")
1970 _ => panic!("Unexpected event"),
1973 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1974 assert_eq!(our_payment_hash_22, *payment_hash);
1975 assert_eq!(recv_value_22, amount_msat);
1977 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1978 assert!(payment_preimage.is_none());
1979 assert_eq!(our_payment_secret_22, *payment_secret);
1981 _ => panic!("expected PaymentPurpose::InvoicePayment")
1984 _ => panic!("Unexpected event"),
1987 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1988 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1989 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1991 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1992 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1993 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1995 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1996 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
1997 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1998 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1999 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2001 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2002 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2006 fn channel_reserve_in_flight_removes() {
2007 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2008 // can send to its counterparty, but due to update ordering, the other side may not yet have
2009 // considered those HTLCs fully removed.
2010 // This tests that we don't count HTLCs which will not be included in the next remote
2011 // commitment transaction towards the reserve value (as it implies no commitment transaction
2012 // will be generated which violates the remote reserve value).
2013 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2015 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2016 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2017 // you only consider the value of the first HTLC, it may not),
2018 // * start routing a third HTLC from A to B,
2019 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2020 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2021 // * deliver the first fulfill from B
2022 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2024 // * deliver A's response CS and RAA.
2025 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2026 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2027 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2028 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2029 let chanmon_cfgs = create_chanmon_cfgs(2);
2030 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2031 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2032 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2033 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2035 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2036 // Route the first two HTLCs.
2037 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2038 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2039 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2041 // Start routing the third HTLC (this is just used to get everyone in the right state).
2042 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2044 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2045 check_added_monitors!(nodes[0], 1);
2046 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2047 assert_eq!(events.len(), 1);
2048 SendEvent::from_event(events.remove(0))
2051 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2052 // initial fulfill/CS.
2053 nodes[1].node.claim_funds(payment_preimage_1);
2054 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2055 check_added_monitors!(nodes[1], 1);
2056 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2058 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2059 // remove the second HTLC when we send the HTLC back from B to A.
2060 nodes[1].node.claim_funds(payment_preimage_2);
2061 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2062 check_added_monitors!(nodes[1], 1);
2063 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2065 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2066 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2067 check_added_monitors!(nodes[0], 1);
2068 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2069 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2071 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2072 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2073 check_added_monitors!(nodes[1], 1);
2074 // B is already AwaitingRAA, so cant generate a CS here
2075 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2077 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2078 check_added_monitors!(nodes[1], 1);
2079 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2081 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2082 check_added_monitors!(nodes[0], 1);
2083 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2085 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2086 check_added_monitors!(nodes[1], 1);
2087 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2089 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2090 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2091 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2092 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2093 // on-chain as necessary).
2094 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2095 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2096 check_added_monitors!(nodes[0], 1);
2097 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2098 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2100 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2101 check_added_monitors!(nodes[1], 1);
2102 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2104 expect_pending_htlcs_forwardable!(nodes[1]);
2105 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2107 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2108 // resolve the second HTLC from A's point of view.
2109 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2110 check_added_monitors!(nodes[0], 1);
2111 expect_payment_path_successful!(nodes[0]);
2112 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2114 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2115 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2116 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2118 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2119 check_added_monitors!(nodes[1], 1);
2120 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2121 assert_eq!(events.len(), 1);
2122 SendEvent::from_event(events.remove(0))
2125 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2126 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2127 check_added_monitors!(nodes[0], 1);
2128 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2130 // Now just resolve all the outstanding messages/HTLCs for completeness...
2132 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2133 check_added_monitors!(nodes[1], 1);
2134 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2136 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2137 check_added_monitors!(nodes[1], 1);
2139 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2140 check_added_monitors!(nodes[0], 1);
2141 expect_payment_path_successful!(nodes[0]);
2142 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2144 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2145 check_added_monitors!(nodes[1], 1);
2146 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2148 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2149 check_added_monitors!(nodes[0], 1);
2151 expect_pending_htlcs_forwardable!(nodes[0]);
2152 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2154 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2155 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2159 fn channel_monitor_network_test() {
2160 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2161 // tests that ChannelMonitor is able to recover from various states.
2162 let chanmon_cfgs = create_chanmon_cfgs(5);
2163 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2164 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2165 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2167 // Create some initial channels
2168 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2169 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2170 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2171 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2173 // Make sure all nodes are at the same starting height
2174 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2175 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2176 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2177 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2178 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2180 // Rebalance the network a bit by relaying one payment through all the channels...
2181 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2182 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2183 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2184 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2186 // Simple case with no pending HTLCs:
2187 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2188 check_added_monitors!(nodes[1], 1);
2189 check_closed_broadcast!(nodes[1], true);
2191 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2192 assert_eq!(node_txn.len(), 1);
2193 mine_transaction(&nodes[0], &node_txn[0]);
2194 check_added_monitors!(nodes[0], 1);
2195 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2197 check_closed_broadcast!(nodes[0], true);
2198 assert_eq!(nodes[0].node.list_channels().len(), 0);
2199 assert_eq!(nodes[1].node.list_channels().len(), 1);
2200 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2201 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2203 // One pending HTLC is discarded by the force-close:
2204 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2206 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2207 // broadcasted until we reach the timelock time).
2208 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2209 check_closed_broadcast!(nodes[1], true);
2210 check_added_monitors!(nodes[1], 1);
2212 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2213 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2214 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2215 mine_transaction(&nodes[2], &node_txn[0]);
2216 check_added_monitors!(nodes[2], 1);
2217 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2219 check_closed_broadcast!(nodes[2], true);
2220 assert_eq!(nodes[1].node.list_channels().len(), 0);
2221 assert_eq!(nodes[2].node.list_channels().len(), 1);
2222 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2223 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2225 macro_rules! claim_funds {
2226 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2228 $node.node.claim_funds($preimage);
2229 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2230 check_added_monitors!($node, 1);
2232 let events = $node.node.get_and_clear_pending_msg_events();
2233 assert_eq!(events.len(), 1);
2235 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2236 assert!(update_add_htlcs.is_empty());
2237 assert!(update_fail_htlcs.is_empty());
2238 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2240 _ => panic!("Unexpected event"),
2246 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2247 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2248 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2249 check_added_monitors!(nodes[2], 1);
2250 check_closed_broadcast!(nodes[2], true);
2251 let node2_commitment_txid;
2253 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2254 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2255 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2256 node2_commitment_txid = node_txn[0].txid();
2258 // Claim the payment on nodes[3], giving it knowledge of the preimage
2259 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2260 mine_transaction(&nodes[3], &node_txn[0]);
2261 check_added_monitors!(nodes[3], 1);
2262 check_preimage_claim(&nodes[3], &node_txn);
2264 check_closed_broadcast!(nodes[3], true);
2265 assert_eq!(nodes[2].node.list_channels().len(), 0);
2266 assert_eq!(nodes[3].node.list_channels().len(), 1);
2267 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2268 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2270 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2271 // confusing us in the following tests.
2272 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2274 // One pending HTLC to time out:
2275 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2276 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2279 let (close_chan_update_1, close_chan_update_2) = {
2280 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2281 let events = nodes[3].node.get_and_clear_pending_msg_events();
2282 assert_eq!(events.len(), 2);
2283 let close_chan_update_1 = match events[0] {
2284 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2287 _ => panic!("Unexpected event"),
2290 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2291 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2293 _ => panic!("Unexpected event"),
2295 check_added_monitors!(nodes[3], 1);
2297 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2299 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2300 node_txn.retain(|tx| {
2301 if tx.input[0].previous_output.txid == node2_commitment_txid {
2307 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2309 // Claim the payment on nodes[4], giving it knowledge of the preimage
2310 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2312 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2313 let events = nodes[4].node.get_and_clear_pending_msg_events();
2314 assert_eq!(events.len(), 2);
2315 let close_chan_update_2 = match events[0] {
2316 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2319 _ => panic!("Unexpected event"),
2322 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2323 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2325 _ => panic!("Unexpected event"),
2327 check_added_monitors!(nodes[4], 1);
2328 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2330 mine_transaction(&nodes[4], &node_txn[0]);
2331 check_preimage_claim(&nodes[4], &node_txn);
2332 (close_chan_update_1, close_chan_update_2)
2334 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2335 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2336 assert_eq!(nodes[3].node.list_channels().len(), 0);
2337 assert_eq!(nodes[4].node.list_channels().len(), 0);
2339 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2340 ChannelMonitorUpdateStatus::Completed);
2341 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2342 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2346 fn test_justice_tx() {
2347 // Test justice txn built on revoked HTLC-Success tx, against both sides
2348 let mut alice_config = UserConfig::default();
2349 alice_config.channel_handshake_config.announced_channel = true;
2350 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2351 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2352 let mut bob_config = UserConfig::default();
2353 bob_config.channel_handshake_config.announced_channel = true;
2354 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2355 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2356 let user_cfgs = [Some(alice_config), Some(bob_config)];
2357 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2358 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2359 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2363 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2364 // Create some new channels:
2365 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2367 // A pending HTLC which will be revoked:
2368 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2369 // Get the will-be-revoked local txn from nodes[0]
2370 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2371 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2372 assert_eq!(revoked_local_txn[0].input.len(), 1);
2373 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2374 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2375 assert_eq!(revoked_local_txn[1].input.len(), 1);
2376 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2377 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2378 // Revoke the old state
2379 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2382 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2384 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2385 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2386 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2388 check_spends!(node_txn[0], revoked_local_txn[0]);
2389 node_txn.swap_remove(0);
2390 node_txn.truncate(1);
2392 check_added_monitors!(nodes[1], 1);
2393 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2394 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2396 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2397 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2398 // Verify broadcast of revoked HTLC-timeout
2399 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2400 check_added_monitors!(nodes[0], 1);
2401 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2402 // Broadcast revoked HTLC-timeout on node 1
2403 mine_transaction(&nodes[1], &node_txn[1]);
2404 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2406 get_announce_close_broadcast_events(&nodes, 0, 1);
2408 assert_eq!(nodes[0].node.list_channels().len(), 0);
2409 assert_eq!(nodes[1].node.list_channels().len(), 0);
2411 // We test justice_tx build by A on B's revoked HTLC-Success tx
2412 // Create some new channels:
2413 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2415 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2419 // A pending HTLC which will be revoked:
2420 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2421 // Get the will-be-revoked local txn from B
2422 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2423 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2424 assert_eq!(revoked_local_txn[0].input.len(), 1);
2425 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2426 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2427 // Revoke the old state
2428 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2430 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2432 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2433 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2434 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2436 check_spends!(node_txn[0], revoked_local_txn[0]);
2437 node_txn.swap_remove(0);
2439 check_added_monitors!(nodes[0], 1);
2440 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2442 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2443 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2444 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2445 check_added_monitors!(nodes[1], 1);
2446 mine_transaction(&nodes[0], &node_txn[1]);
2447 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2448 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2450 get_announce_close_broadcast_events(&nodes, 0, 1);
2451 assert_eq!(nodes[0].node.list_channels().len(), 0);
2452 assert_eq!(nodes[1].node.list_channels().len(), 0);
2456 fn revoked_output_claim() {
2457 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2458 // transaction is broadcast by its counterparty
2459 let chanmon_cfgs = create_chanmon_cfgs(2);
2460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2462 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2463 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2464 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2465 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2466 assert_eq!(revoked_local_txn.len(), 1);
2467 // Only output is the full channel value back to nodes[0]:
2468 assert_eq!(revoked_local_txn[0].output.len(), 1);
2469 // Send a payment through, updating everyone's latest commitment txn
2470 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2472 // Inform nodes[1] that nodes[0] broadcast a stale tx
2473 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2474 check_added_monitors!(nodes[1], 1);
2475 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2476 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2477 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2479 check_spends!(node_txn[0], revoked_local_txn[0]);
2480 check_spends!(node_txn[1], chan_1.3);
2482 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2483 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2484 get_announce_close_broadcast_events(&nodes, 0, 1);
2485 check_added_monitors!(nodes[0], 1);
2486 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2490 fn claim_htlc_outputs_shared_tx() {
2491 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2492 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2493 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2494 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2495 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2496 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2498 // Create some new channel:
2499 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2501 // Rebalance the network to generate htlc in the two directions
2502 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2503 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2504 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2505 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2507 // Get the will-be-revoked local txn from node[0]
2508 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2509 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2510 assert_eq!(revoked_local_txn[0].input.len(), 1);
2511 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2512 assert_eq!(revoked_local_txn[1].input.len(), 1);
2513 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2514 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2515 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2517 //Revoke the old state
2518 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2521 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2522 check_added_monitors!(nodes[0], 1);
2523 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2524 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2525 check_added_monitors!(nodes[1], 1);
2526 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2527 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2528 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2530 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2531 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2533 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2534 check_spends!(node_txn[0], revoked_local_txn[0]);
2536 let mut witness_lens = BTreeSet::new();
2537 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2538 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2539 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2540 assert_eq!(witness_lens.len(), 3);
2541 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2542 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2543 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2545 // Next nodes[1] broadcasts its current local tx state:
2546 assert_eq!(node_txn[1].input.len(), 1);
2547 check_spends!(node_txn[1], chan_1.3);
2549 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2550 // ANTI_REORG_DELAY confirmations.
2551 mine_transaction(&nodes[1], &node_txn[0]);
2552 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2553 expect_payment_failed!(nodes[1], payment_hash_2, false);
2555 get_announce_close_broadcast_events(&nodes, 0, 1);
2556 assert_eq!(nodes[0].node.list_channels().len(), 0);
2557 assert_eq!(nodes[1].node.list_channels().len(), 0);
2561 fn claim_htlc_outputs_single_tx() {
2562 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2563 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2564 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2565 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2566 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2567 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2569 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2571 // Rebalance the network to generate htlc in the two directions
2572 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2573 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2574 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2575 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2576 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2578 // Get the will-be-revoked local txn from node[0]
2579 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2581 //Revoke the old state
2582 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2585 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2586 check_added_monitors!(nodes[0], 1);
2587 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2588 check_added_monitors!(nodes[1], 1);
2589 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2590 let mut events = nodes[0].node.get_and_clear_pending_events();
2591 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2592 match events.last().unwrap() {
2593 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2594 _ => panic!("Unexpected event"),
2597 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2598 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2600 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2601 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2603 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2604 assert_eq!(node_txn[0].input.len(), 1);
2605 check_spends!(node_txn[0], chan_1.3);
2606 assert_eq!(node_txn[1].input.len(), 1);
2607 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2608 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2609 check_spends!(node_txn[1], node_txn[0]);
2611 // Justice transactions are indices 1-2-4
2612 assert_eq!(node_txn[2].input.len(), 1);
2613 assert_eq!(node_txn[3].input.len(), 1);
2614 assert_eq!(node_txn[4].input.len(), 1);
2616 check_spends!(node_txn[2], revoked_local_txn[0]);
2617 check_spends!(node_txn[3], revoked_local_txn[0]);
2618 check_spends!(node_txn[4], revoked_local_txn[0]);
2620 let mut witness_lens = BTreeSet::new();
2621 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2622 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2623 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2624 assert_eq!(witness_lens.len(), 3);
2625 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2626 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2627 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2629 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2630 // ANTI_REORG_DELAY confirmations.
2631 mine_transaction(&nodes[1], &node_txn[2]);
2632 mine_transaction(&nodes[1], &node_txn[3]);
2633 mine_transaction(&nodes[1], &node_txn[4]);
2634 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2635 expect_payment_failed!(nodes[1], payment_hash_2, false);
2637 get_announce_close_broadcast_events(&nodes, 0, 1);
2638 assert_eq!(nodes[0].node.list_channels().len(), 0);
2639 assert_eq!(nodes[1].node.list_channels().len(), 0);
2643 fn test_htlc_on_chain_success() {
2644 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2645 // the preimage backward accordingly. So here we test that ChannelManager is
2646 // broadcasting the right event to other nodes in payment path.
2647 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2648 // A --------------------> B ----------------------> C (preimage)
2649 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2650 // commitment transaction was broadcast.
2651 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2653 // B should be able to claim via preimage if A then broadcasts its local tx.
2654 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2655 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2656 // PaymentSent event).
2658 let chanmon_cfgs = create_chanmon_cfgs(3);
2659 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2660 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2661 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2663 // Create some initial channels
2664 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2665 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2667 // Ensure all nodes are at the same height
2668 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2669 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2670 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2671 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2673 // Rebalance the network a bit by relaying one payment through all the channels...
2674 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2675 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2677 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2678 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2680 // Broadcast legit commitment tx from C on B's chain
2681 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2682 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2683 assert_eq!(commitment_tx.len(), 1);
2684 check_spends!(commitment_tx[0], chan_2.3);
2685 nodes[2].node.claim_funds(our_payment_preimage);
2686 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2687 nodes[2].node.claim_funds(our_payment_preimage_2);
2688 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2689 check_added_monitors!(nodes[2], 2);
2690 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2691 assert!(updates.update_add_htlcs.is_empty());
2692 assert!(updates.update_fail_htlcs.is_empty());
2693 assert!(updates.update_fail_malformed_htlcs.is_empty());
2694 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2696 mine_transaction(&nodes[2], &commitment_tx[0]);
2697 check_closed_broadcast!(nodes[2], true);
2698 check_added_monitors!(nodes[2], 1);
2699 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2700 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2701 assert_eq!(node_txn.len(), 5);
2702 assert_eq!(node_txn[0], node_txn[3]);
2703 assert_eq!(node_txn[1], node_txn[4]);
2704 assert_eq!(node_txn[2], commitment_tx[0]);
2705 check_spends!(node_txn[0], commitment_tx[0]);
2706 check_spends!(node_txn[1], commitment_tx[0]);
2707 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2708 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2709 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2710 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2711 assert_eq!(node_txn[0].lock_time.0, 0);
2712 assert_eq!(node_txn[1].lock_time.0, 0);
2714 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2715 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2716 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2717 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2719 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2720 assert_eq!(added_monitors.len(), 1);
2721 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2722 added_monitors.clear();
2724 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2725 assert_eq!(forwarded_events.len(), 3);
2726 match forwarded_events[0] {
2727 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2728 _ => panic!("Unexpected event"),
2730 let chan_id = Some(chan_1.2);
2731 match forwarded_events[1] {
2732 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2733 assert_eq!(fee_earned_msat, Some(1000));
2734 assert_eq!(prev_channel_id, chan_id);
2735 assert_eq!(claim_from_onchain_tx, true);
2736 assert_eq!(next_channel_id, Some(chan_2.2));
2740 match forwarded_events[2] {
2741 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2742 assert_eq!(fee_earned_msat, Some(1000));
2743 assert_eq!(prev_channel_id, chan_id);
2744 assert_eq!(claim_from_onchain_tx, true);
2745 assert_eq!(next_channel_id, Some(chan_2.2));
2749 let events = nodes[1].node.get_and_clear_pending_msg_events();
2751 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2752 assert_eq!(added_monitors.len(), 2);
2753 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2754 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2755 added_monitors.clear();
2757 assert_eq!(events.len(), 3);
2759 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2760 _ => panic!("Unexpected event"),
2763 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2764 _ => panic!("Unexpected event"),
2768 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2769 assert!(update_add_htlcs.is_empty());
2770 assert!(update_fail_htlcs.is_empty());
2771 assert_eq!(update_fulfill_htlcs.len(), 1);
2772 assert!(update_fail_malformed_htlcs.is_empty());
2773 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2775 _ => panic!("Unexpected event"),
2777 macro_rules! check_tx_local_broadcast {
2778 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2779 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2780 assert_eq!(node_txn.len(), 3);
2781 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2782 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2783 check_spends!(node_txn[1], $commitment_tx);
2784 check_spends!(node_txn[2], $commitment_tx);
2785 assert_ne!(node_txn[1].lock_time.0, 0);
2786 assert_ne!(node_txn[2].lock_time.0, 0);
2788 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2789 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2790 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2791 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2793 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2794 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2795 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2796 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2798 check_spends!(node_txn[0], $chan_tx);
2799 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2803 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2804 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2805 // timeout-claim of the output that nodes[2] just claimed via success.
2806 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2808 // Broadcast legit commitment tx from A on B's chain
2809 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2810 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2811 check_spends!(node_a_commitment_tx[0], chan_1.3);
2812 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2813 check_closed_broadcast!(nodes[1], true);
2814 check_added_monitors!(nodes[1], 1);
2815 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2816 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2817 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2818 let commitment_spend =
2819 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2820 check_spends!(node_txn[1], commitment_tx[0]);
2821 check_spends!(node_txn[2], commitment_tx[0]);
2822 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2825 check_spends!(node_txn[0], commitment_tx[0]);
2826 check_spends!(node_txn[1], commitment_tx[0]);
2827 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2831 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2832 assert_eq!(commitment_spend.input.len(), 2);
2833 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2834 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2835 assert_eq!(commitment_spend.lock_time.0, 0);
2836 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2837 check_spends!(node_txn[3], chan_1.3);
2838 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2839 check_spends!(node_txn[4], node_txn[3]);
2840 check_spends!(node_txn[5], node_txn[3]);
2841 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2842 // we already checked the same situation with A.
2844 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2845 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2846 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2847 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2848 check_closed_broadcast!(nodes[0], true);
2849 check_added_monitors!(nodes[0], 1);
2850 let events = nodes[0].node.get_and_clear_pending_events();
2851 assert_eq!(events.len(), 5);
2852 let mut first_claimed = false;
2853 for event in events {
2855 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2856 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2857 assert!(!first_claimed);
2858 first_claimed = true;
2860 assert_eq!(payment_preimage, our_payment_preimage_2);
2861 assert_eq!(payment_hash, payment_hash_2);
2864 Event::PaymentPathSuccessful { .. } => {},
2865 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2866 _ => panic!("Unexpected event"),
2869 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2872 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2873 // Test that in case of a unilateral close onchain, we detect the state of output and
2874 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2875 // broadcasting the right event to other nodes in payment path.
2876 // A ------------------> B ----------------------> C (timeout)
2877 // B's commitment tx C's commitment tx
2879 // B's HTLC timeout tx B's timeout tx
2881 let chanmon_cfgs = create_chanmon_cfgs(3);
2882 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2883 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2884 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2885 *nodes[0].connect_style.borrow_mut() = connect_style;
2886 *nodes[1].connect_style.borrow_mut() = connect_style;
2887 *nodes[2].connect_style.borrow_mut() = connect_style;
2889 // Create some intial channels
2890 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2891 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2893 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2894 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2895 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2897 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2899 // Broadcast legit commitment tx from C on B's chain
2900 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2901 check_spends!(commitment_tx[0], chan_2.3);
2902 nodes[2].node.fail_htlc_backwards(&payment_hash);
2903 check_added_monitors!(nodes[2], 0);
2904 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2905 check_added_monitors!(nodes[2], 1);
2907 let events = nodes[2].node.get_and_clear_pending_msg_events();
2908 assert_eq!(events.len(), 1);
2910 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, .. } } => {
2911 assert!(update_add_htlcs.is_empty());
2912 assert!(!update_fail_htlcs.is_empty());
2913 assert!(update_fulfill_htlcs.is_empty());
2914 assert!(update_fail_malformed_htlcs.is_empty());
2915 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2917 _ => panic!("Unexpected event"),
2919 mine_transaction(&nodes[2], &commitment_tx[0]);
2920 check_closed_broadcast!(nodes[2], true);
2921 check_added_monitors!(nodes[2], 1);
2922 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2923 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2924 assert_eq!(node_txn.len(), 1);
2925 check_spends!(node_txn[0], chan_2.3);
2926 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2928 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2929 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2930 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2931 mine_transaction(&nodes[1], &commitment_tx[0]);
2932 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2935 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2936 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2937 assert_eq!(node_txn[0], node_txn[3]);
2938 assert_eq!(node_txn[1], node_txn[4]);
2940 check_spends!(node_txn[2], commitment_tx[0]);
2941 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2943 check_spends!(node_txn[0], chan_2.3);
2944 check_spends!(node_txn[1], node_txn[0]);
2945 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2946 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2948 timeout_tx = node_txn[2].clone();
2952 mine_transaction(&nodes[1], &timeout_tx);
2953 check_added_monitors!(nodes[1], 1);
2954 check_closed_broadcast!(nodes[1], true);
2956 // B will rebroadcast a fee-bumped timeout transaction here.
2957 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2958 assert_eq!(node_txn.len(), 1);
2959 check_spends!(node_txn[0], commitment_tx[0]);
2962 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2964 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2965 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2966 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2967 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2968 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2969 if node_txn.len() == 1 {
2970 check_spends!(node_txn[0], chan_2.3);
2972 assert_eq!(node_txn.len(), 0);
2976 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 }]);
2977 check_added_monitors!(nodes[1], 1);
2978 let events = nodes[1].node.get_and_clear_pending_msg_events();
2979 assert_eq!(events.len(), 1);
2981 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, .. } } => {
2982 assert!(update_add_htlcs.is_empty());
2983 assert!(!update_fail_htlcs.is_empty());
2984 assert!(update_fulfill_htlcs.is_empty());
2985 assert!(update_fail_malformed_htlcs.is_empty());
2986 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2988 _ => panic!("Unexpected event"),
2991 // Broadcast legit commitment tx from B on A's chain
2992 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2993 check_spends!(commitment_tx[0], chan_1.3);
2995 mine_transaction(&nodes[0], &commitment_tx[0]);
2996 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2998 check_closed_broadcast!(nodes[0], true);
2999 check_added_monitors!(nodes[0], 1);
3000 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3001 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3002 assert_eq!(node_txn.len(), 2);
3003 check_spends!(node_txn[0], chan_1.3);
3004 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3005 check_spends!(node_txn[1], commitment_tx[0]);
3006 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3010 fn test_htlc_on_chain_timeout() {
3011 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3012 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3013 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3017 fn test_simple_commitment_revoked_fail_backward() {
3018 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3019 // and fail backward accordingly.
3021 let chanmon_cfgs = create_chanmon_cfgs(3);
3022 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3023 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3024 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3026 // Create some initial channels
3027 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3028 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3030 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3031 // Get the will-be-revoked local txn from nodes[2]
3032 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3033 // Revoke the old state
3034 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3036 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3038 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3039 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3040 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3041 check_added_monitors!(nodes[1], 1);
3042 check_closed_broadcast!(nodes[1], true);
3044 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 }]);
3045 check_added_monitors!(nodes[1], 1);
3046 let events = nodes[1].node.get_and_clear_pending_msg_events();
3047 assert_eq!(events.len(), 1);
3049 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, .. } } => {
3050 assert!(update_add_htlcs.is_empty());
3051 assert_eq!(update_fail_htlcs.len(), 1);
3052 assert!(update_fulfill_htlcs.is_empty());
3053 assert!(update_fail_malformed_htlcs.is_empty());
3054 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3056 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3057 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3058 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3060 _ => panic!("Unexpected event"),
3064 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3065 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3066 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3067 // commitment transaction anymore.
3068 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3069 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3070 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3071 // technically disallowed and we should probably handle it reasonably.
3072 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3073 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3075 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3076 // commitment_signed (implying it will be in the latest remote commitment transaction).
3077 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3078 // and once they revoke the previous commitment transaction (allowing us to send a new
3079 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3080 let chanmon_cfgs = create_chanmon_cfgs(3);
3081 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3082 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3083 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3085 // Create some initial channels
3086 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3087 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3089 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 });
3090 // Get the will-be-revoked local txn from nodes[2]
3091 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3092 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3093 // Revoke the old state
3094 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3096 let value = if use_dust {
3097 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3098 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3099 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3102 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3103 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3104 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3106 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3107 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3108 check_added_monitors!(nodes[2], 1);
3109 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3110 assert!(updates.update_add_htlcs.is_empty());
3111 assert!(updates.update_fulfill_htlcs.is_empty());
3112 assert!(updates.update_fail_malformed_htlcs.is_empty());
3113 assert_eq!(updates.update_fail_htlcs.len(), 1);
3114 assert!(updates.update_fee.is_none());
3115 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3116 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3117 // Drop the last RAA from 3 -> 2
3119 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3120 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_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 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3130 check_added_monitors!(nodes[1], 1);
3131 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3132 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3133 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3134 check_added_monitors!(nodes[2], 1);
3136 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3137 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3138 check_added_monitors!(nodes[2], 1);
3139 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3140 assert!(updates.update_add_htlcs.is_empty());
3141 assert!(updates.update_fulfill_htlcs.is_empty());
3142 assert!(updates.update_fail_malformed_htlcs.is_empty());
3143 assert_eq!(updates.update_fail_htlcs.len(), 1);
3144 assert!(updates.update_fee.is_none());
3145 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3146 // At this point first_payment_hash has dropped out of the latest two commitment
3147 // transactions that nodes[1] is tracking...
3148 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3149 check_added_monitors!(nodes[1], 1);
3150 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3151 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3152 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3153 check_added_monitors!(nodes[2], 1);
3155 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3156 // on nodes[2]'s RAA.
3157 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3158 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3159 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3160 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3161 check_added_monitors!(nodes[1], 0);
3164 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3165 // One monitor for the new revocation preimage, no second on as we won't generate a new
3166 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3167 check_added_monitors!(nodes[1], 1);
3168 let events = nodes[1].node.get_and_clear_pending_events();
3169 assert_eq!(events.len(), 2);
3171 Event::PendingHTLCsForwardable { .. } => { },
3172 _ => panic!("Unexpected event"),
3175 Event::HTLCHandlingFailed { .. } => { },
3176 _ => panic!("Unexpected event"),
3178 // Deliberately don't process the pending fail-back so they all fail back at once after
3179 // block connection just like the !deliver_bs_raa case
3182 let mut failed_htlcs = HashSet::new();
3183 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3185 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3186 check_added_monitors!(nodes[1], 1);
3187 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3188 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3190 let events = nodes[1].node.get_and_clear_pending_events();
3191 assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3193 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3194 _ => panic!("Unexepected event"),
3197 Event::PaymentPathFailed { ref payment_hash, .. } => {
3198 assert_eq!(*payment_hash, fourth_payment_hash);
3200 _ => panic!("Unexpected event"),
3202 if !deliver_bs_raa {
3204 Event::PaymentFailed { ref payment_hash, .. } => {
3205 assert_eq!(*payment_hash, fourth_payment_hash);
3207 _ => panic!("Unexpected event"),
3210 Event::PendingHTLCsForwardable { .. } => { },
3211 _ => panic!("Unexpected event"),
3214 nodes[1].node.process_pending_htlc_forwards();
3215 check_added_monitors!(nodes[1], 1);
3217 let events = nodes[1].node.get_and_clear_pending_msg_events();
3218 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3219 match events[if deliver_bs_raa { 1 } else { 0 }] {
3220 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3221 _ => panic!("Unexpected event"),
3223 match events[if deliver_bs_raa { 2 } else { 1 }] {
3224 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3225 assert_eq!(channel_id, chan_2.2);
3226 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3228 _ => panic!("Unexpected event"),
3232 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, .. } } => {
3233 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3234 assert_eq!(update_add_htlcs.len(), 1);
3235 assert!(update_fulfill_htlcs.is_empty());
3236 assert!(update_fail_htlcs.is_empty());
3237 assert!(update_fail_malformed_htlcs.is_empty());
3239 _ => panic!("Unexpected event"),
3242 match events[if deliver_bs_raa { 3 } else { 2 }] {
3243 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, .. } } => {
3244 assert!(update_add_htlcs.is_empty());
3245 assert_eq!(update_fail_htlcs.len(), 3);
3246 assert!(update_fulfill_htlcs.is_empty());
3247 assert!(update_fail_malformed_htlcs.is_empty());
3248 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3250 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3251 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3252 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3254 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3256 let events = nodes[0].node.get_and_clear_pending_events();
3257 assert_eq!(events.len(), 3);
3259 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3260 assert!(failed_htlcs.insert(payment_hash.0));
3261 // If we delivered B's RAA we got an unknown preimage error, not something
3262 // that we should update our routing table for.
3263 if !deliver_bs_raa {
3264 assert!(network_update.is_some());
3267 _ => panic!("Unexpected event"),
3270 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3271 assert!(failed_htlcs.insert(payment_hash.0));
3272 assert!(network_update.is_some());
3274 _ => panic!("Unexpected event"),
3277 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3278 assert!(failed_htlcs.insert(payment_hash.0));
3279 assert!(network_update.is_some());
3281 _ => panic!("Unexpected event"),
3284 _ => panic!("Unexpected event"),
3287 assert!(failed_htlcs.contains(&first_payment_hash.0));
3288 assert!(failed_htlcs.contains(&second_payment_hash.0));
3289 assert!(failed_htlcs.contains(&third_payment_hash.0));
3293 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3294 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3295 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3296 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3297 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3301 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3302 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3303 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3304 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3305 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3309 fn fail_backward_pending_htlc_upon_channel_failure() {
3310 let chanmon_cfgs = create_chanmon_cfgs(2);
3311 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3312 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3313 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3314 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3316 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3318 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3319 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3320 check_added_monitors!(nodes[0], 1);
3322 let payment_event = {
3323 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3324 assert_eq!(events.len(), 1);
3325 SendEvent::from_event(events.remove(0))
3327 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3328 assert_eq!(payment_event.msgs.len(), 1);
3331 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3332 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3334 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3335 check_added_monitors!(nodes[0], 0);
3337 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3340 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3342 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3344 let secp_ctx = Secp256k1::new();
3345 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3346 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3347 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3348 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3349 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3351 // Send a 0-msat update_add_htlc to fail the channel.
3352 let update_add_htlc = msgs::UpdateAddHTLC {
3358 onion_routing_packet,
3360 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3362 let events = nodes[0].node.get_and_clear_pending_events();
3363 assert_eq!(events.len(), 2);
3364 // Check that Alice fails backward the pending HTLC from the second payment.
3366 Event::PaymentPathFailed { payment_hash, .. } => {
3367 assert_eq!(payment_hash, failed_payment_hash);
3369 _ => panic!("Unexpected event"),
3372 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3373 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3375 _ => panic!("Unexpected event {:?}", events[1]),
3377 check_closed_broadcast!(nodes[0], true);
3378 check_added_monitors!(nodes[0], 1);
3382 fn test_htlc_ignore_latest_remote_commitment() {
3383 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3384 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3385 let chanmon_cfgs = create_chanmon_cfgs(2);
3386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3389 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
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 header.prev_blockhash = header.block_hash();
3411 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3415 fn test_force_close_fail_back() {
3416 // Check which HTLCs are failed-backwards on channel force-closure
3417 let chanmon_cfgs = create_chanmon_cfgs(3);
3418 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3419 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3420 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3421 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3422 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3424 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3426 let mut payment_event = {
3427 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3428 check_added_monitors!(nodes[0], 1);
3430 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3431 assert_eq!(events.len(), 1);
3432 SendEvent::from_event(events.remove(0))
3435 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3436 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3438 expect_pending_htlcs_forwardable!(nodes[1]);
3440 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3441 assert_eq!(events_2.len(), 1);
3442 payment_event = SendEvent::from_event(events_2.remove(0));
3443 assert_eq!(payment_event.msgs.len(), 1);
3445 check_added_monitors!(nodes[1], 1);
3446 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3447 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3448 check_added_monitors!(nodes[2], 1);
3449 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3451 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3452 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3453 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3455 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3456 check_closed_broadcast!(nodes[2], true);
3457 check_added_monitors!(nodes[2], 1);
3458 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3460 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3461 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3462 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3463 // back to nodes[1] upon timeout otherwise.
3464 assert_eq!(node_txn.len(), 1);
3468 mine_transaction(&nodes[1], &tx);
3470 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3471 check_closed_broadcast!(nodes[1], true);
3472 check_added_monitors!(nodes[1], 1);
3473 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3475 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3477 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3478 .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);
3480 mine_transaction(&nodes[2], &tx);
3481 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3482 assert_eq!(node_txn.len(), 1);
3483 assert_eq!(node_txn[0].input.len(), 1);
3484 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3485 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3486 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3488 check_spends!(node_txn[0], tx);
3492 fn test_dup_events_on_peer_disconnect() {
3493 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3494 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3495 // as we used to generate the event immediately upon receipt of the payment preimage in the
3496 // update_fulfill_htlc message.
3498 let chanmon_cfgs = create_chanmon_cfgs(2);
3499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3501 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3502 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3504 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3506 nodes[1].node.claim_funds(payment_preimage);
3507 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3508 check_added_monitors!(nodes[1], 1);
3509 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3510 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3511 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3513 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3514 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3516 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3517 expect_payment_path_successful!(nodes[0]);
3521 fn test_peer_disconnected_before_funding_broadcasted() {
3522 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3523 // before the funding transaction has been broadcasted.
3524 let chanmon_cfgs = create_chanmon_cfgs(2);
3525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3529 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3530 // broadcasted, even though it's created by `nodes[0]`.
3531 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();
3532 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3533 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3534 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3535 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3537 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3538 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3540 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3542 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3543 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3545 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3546 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3549 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3552 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3553 // disconnected before the funding transaction was broadcasted.
3554 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3555 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3557 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3558 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3562 fn test_simple_peer_disconnect() {
3563 // Test that we can reconnect when there are no lost messages
3564 let chanmon_cfgs = create_chanmon_cfgs(3);
3565 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3566 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3567 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3568 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3569 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3571 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3575 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3576 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3577 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3578 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3580 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3585 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3586 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3592 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3593 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3595 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3597 let events = nodes[0].node.get_and_clear_pending_events();
3598 assert_eq!(events.len(), 3);
3600 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3601 assert_eq!(payment_preimage, payment_preimage_3);
3602 assert_eq!(payment_hash, payment_hash_3);
3604 _ => panic!("Unexpected event"),
3607 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3608 assert_eq!(payment_hash, payment_hash_5);
3609 assert!(payment_failed_permanently);
3611 _ => panic!("Unexpected event"),
3614 Event::PaymentPathSuccessful { .. } => {},
3615 _ => panic!("Unexpected event"),
3619 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3620 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3623 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3624 // Test that we can reconnect when in-flight HTLC updates get dropped
3625 let chanmon_cfgs = create_chanmon_cfgs(2);
3626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3628 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3630 let mut as_channel_ready = None;
3631 if messages_delivered == 0 {
3632 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3633 as_channel_ready = Some(channel_ready);
3634 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3635 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3636 // it before the channel_reestablish message.
3638 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
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)).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::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3743 assert_eq!(payment_hash_1, *payment_hash);
3744 assert_eq!(amount_msat, 1_000_000);
3746 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3747 assert!(payment_preimage.is_none());
3748 assert_eq!(payment_secret_1, *payment_secret);
3750 _ => panic!("expected PaymentPurpose::InvoicePayment")
3753 _ => panic!("Unexpected event"),
3756 nodes[1].node.claim_funds(payment_preimage_1);
3757 check_added_monitors!(nodes[1], 1);
3758 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3760 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3761 assert_eq!(events_3.len(), 1);
3762 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3763 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3764 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3765 assert!(updates.update_add_htlcs.is_empty());
3766 assert!(updates.update_fail_htlcs.is_empty());
3767 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3768 assert!(updates.update_fail_malformed_htlcs.is_empty());
3769 assert!(updates.update_fee.is_none());
3770 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3772 _ => panic!("Unexpected event"),
3775 if messages_delivered >= 1 {
3776 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3778 let events_4 = nodes[0].node.get_and_clear_pending_events();
3779 assert_eq!(events_4.len(), 1);
3781 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3782 assert_eq!(payment_preimage_1, *payment_preimage);
3783 assert_eq!(payment_hash_1, *payment_hash);
3785 _ => panic!("Unexpected event"),
3788 if messages_delivered >= 2 {
3789 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3790 check_added_monitors!(nodes[0], 1);
3791 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3793 if messages_delivered >= 3 {
3794 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3795 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3796 check_added_monitors!(nodes[1], 1);
3798 if messages_delivered >= 4 {
3799 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3800 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3801 // No commitment_signed so get_event_msg's assert(len == 1) passes
3802 check_added_monitors!(nodes[1], 1);
3804 if messages_delivered >= 5 {
3805 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3806 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3807 check_added_monitors!(nodes[0], 1);
3814 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3815 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3816 if messages_delivered < 2 {
3817 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3818 if messages_delivered < 1 {
3819 expect_payment_sent!(nodes[0], payment_preimage_1);
3821 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3823 } else if messages_delivered == 2 {
3824 // nodes[0] still wants its RAA + commitment_signed
3825 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3826 } else if messages_delivered == 3 {
3827 // nodes[0] still wants its commitment_signed
3828 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3829 } else if messages_delivered == 4 {
3830 // nodes[1] still wants its final RAA
3831 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3832 } else if messages_delivered == 5 {
3833 // Everything was delivered...
3834 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3837 if messages_delivered == 1 || messages_delivered == 2 {
3838 expect_payment_path_successful!(nodes[0]);
3841 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3842 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3843 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3845 if messages_delivered > 2 {
3846 expect_payment_path_successful!(nodes[0]);
3849 // Channel should still work fine...
3850 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3851 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3852 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3856 fn test_drop_messages_peer_disconnect_a() {
3857 do_test_drop_messages_peer_disconnect(0, true);
3858 do_test_drop_messages_peer_disconnect(0, false);
3859 do_test_drop_messages_peer_disconnect(1, false);
3860 do_test_drop_messages_peer_disconnect(2, false);
3864 fn test_drop_messages_peer_disconnect_b() {
3865 do_test_drop_messages_peer_disconnect(3, false);
3866 do_test_drop_messages_peer_disconnect(4, false);
3867 do_test_drop_messages_peer_disconnect(5, false);
3868 do_test_drop_messages_peer_disconnect(6, false);
3872 fn test_funding_peer_disconnect() {
3873 // Test that we can lock in our funding tx while disconnected
3874 let chanmon_cfgs = create_chanmon_cfgs(2);
3875 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3876 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3877 let persister: test_utils::TestPersister;
3878 let new_chain_monitor: test_utils::TestChainMonitor;
3879 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3880 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3881 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3883 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3884 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3886 confirm_transaction(&nodes[0], &tx);
3887 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3888 assert!(events_1.is_empty());
3890 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3892 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3893 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3895 confirm_transaction(&nodes[1], &tx);
3896 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3897 assert!(events_2.is_empty());
3899 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3900 let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
3901 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3902 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
3904 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3905 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3906 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3907 assert_eq!(events_3.len(), 1);
3908 let as_channel_ready = match events_3[0] {
3909 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3910 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3913 _ => panic!("Unexpected event {:?}", events_3[0]),
3916 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3917 // announcement_signatures as well as channel_update.
3918 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3919 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3920 assert_eq!(events_4.len(), 3);
3922 let bs_channel_ready = match events_4[0] {
3923 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3924 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3925 chan_id = msg.channel_id;
3928 _ => panic!("Unexpected event {:?}", events_4[0]),
3930 let bs_announcement_sigs = match events_4[1] {
3931 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3932 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3935 _ => panic!("Unexpected event {:?}", events_4[1]),
3938 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3939 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3941 _ => panic!("Unexpected event {:?}", events_4[2]),
3944 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3945 // generates a duplicative private channel_update
3946 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3947 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3948 assert_eq!(events_5.len(), 1);
3950 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3951 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3953 _ => panic!("Unexpected event {:?}", events_5[0]),
3956 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3957 // announcement_signatures.
3958 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3959 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3960 assert_eq!(events_6.len(), 1);
3961 let as_announcement_sigs = match events_6[0] {
3962 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3963 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3966 _ => panic!("Unexpected event {:?}", events_6[0]),
3968 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
3969 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
3971 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3972 // broadcast the channel announcement globally, as well as re-send its (now-public)
3974 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3975 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3976 assert_eq!(events_7.len(), 1);
3977 let (chan_announcement, as_update) = match events_7[0] {
3978 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3979 (msg.clone(), update_msg.clone())
3981 _ => panic!("Unexpected event {:?}", events_7[0]),
3984 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3985 // same channel_announcement.
3986 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3987 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3988 assert_eq!(events_8.len(), 1);
3989 let bs_update = match events_8[0] {
3990 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3991 assert_eq!(*msg, chan_announcement);
3994 _ => panic!("Unexpected event {:?}", events_8[0]),
3997 // Provide the channel announcement and public updates to the network graph
3998 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3999 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
4000 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
4002 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4003 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4004 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4006 // Check that after deserialization and reconnection we can still generate an identical
4007 // channel_announcement from the cached signatures.
4008 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4010 let nodes_0_serialized = nodes[0].node.encode();
4011 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4012 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4014 persister = test_utils::TestPersister::new();
4015 let keys_manager = &chanmon_cfgs[0].keys_manager;
4016 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
4017 nodes[0].chain_monitor = &new_chain_monitor;
4018 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4019 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4020 &mut chan_0_monitor_read, keys_manager).unwrap();
4021 assert!(chan_0_monitor_read.is_empty());
4023 let mut nodes_0_read = &nodes_0_serialized[..];
4024 let (_, nodes_0_deserialized_tmp) = {
4025 let mut channel_monitors = HashMap::new();
4026 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4027 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4028 default_config: UserConfig::default(),
4030 fee_estimator: node_cfgs[0].fee_estimator,
4031 chain_monitor: nodes[0].chain_monitor,
4032 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4033 logger: nodes[0].logger,
4037 nodes_0_deserialized = nodes_0_deserialized_tmp;
4038 assert!(nodes_0_read.is_empty());
4040 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4041 ChannelMonitorUpdateStatus::Completed);
4042 nodes[0].node = &nodes_0_deserialized;
4043 check_added_monitors!(nodes[0], 1);
4045 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4049 fn test_channel_ready_without_best_block_updated() {
4050 // Previously, if we were offline when a funding transaction was locked in, and then we came
4051 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4052 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4053 // channel_ready immediately instead.
4054 let chanmon_cfgs = create_chanmon_cfgs(2);
4055 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4056 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4057 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4058 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4060 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4062 let conf_height = nodes[0].best_block_info().1 + 1;
4063 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4064 let block_txn = [funding_tx];
4065 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4066 let conf_block_header = nodes[0].get_block_header(conf_height);
4067 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4069 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4070 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4071 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4075 fn test_drop_messages_peer_disconnect_dual_htlc() {
4076 // Test that we can handle reconnecting when both sides of a channel have pending
4077 // commitment_updates when we disconnect.
4078 let chanmon_cfgs = create_chanmon_cfgs(2);
4079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4081 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4082 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4084 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4086 // Now try to send a second payment which will fail to send
4087 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4088 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4089 check_added_monitors!(nodes[0], 1);
4091 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4092 assert_eq!(events_1.len(), 1);
4094 MessageSendEvent::UpdateHTLCs { .. } => {},
4095 _ => panic!("Unexpected event"),
4098 nodes[1].node.claim_funds(payment_preimage_1);
4099 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4100 check_added_monitors!(nodes[1], 1);
4102 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4103 assert_eq!(events_2.len(), 1);
4105 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 } } => {
4106 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4107 assert!(update_add_htlcs.is_empty());
4108 assert_eq!(update_fulfill_htlcs.len(), 1);
4109 assert!(update_fail_htlcs.is_empty());
4110 assert!(update_fail_malformed_htlcs.is_empty());
4111 assert!(update_fee.is_none());
4113 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4114 let events_3 = nodes[0].node.get_and_clear_pending_events();
4115 assert_eq!(events_3.len(), 1);
4117 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4118 assert_eq!(*payment_preimage, payment_preimage_1);
4119 assert_eq!(*payment_hash, payment_hash_1);
4121 _ => panic!("Unexpected event"),
4124 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4125 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4126 // No commitment_signed so get_event_msg's assert(len == 1) passes
4127 check_added_monitors!(nodes[0], 1);
4129 _ => panic!("Unexpected event"),
4132 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4133 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4135 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4136 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4137 assert_eq!(reestablish_1.len(), 1);
4138 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4139 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4140 assert_eq!(reestablish_2.len(), 1);
4142 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4143 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4144 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4145 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4147 assert!(as_resp.0.is_none());
4148 assert!(bs_resp.0.is_none());
4150 assert!(bs_resp.1.is_none());
4151 assert!(bs_resp.2.is_none());
4153 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4155 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4156 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4157 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4158 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4159 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4160 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4161 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4162 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4163 // No commitment_signed so get_event_msg's assert(len == 1) passes
4164 check_added_monitors!(nodes[1], 1);
4166 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4167 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4168 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4169 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4170 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4171 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4172 assert!(bs_second_commitment_signed.update_fee.is_none());
4173 check_added_monitors!(nodes[1], 1);
4175 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4176 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4177 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4178 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4179 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4180 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4181 assert!(as_commitment_signed.update_fee.is_none());
4182 check_added_monitors!(nodes[0], 1);
4184 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4185 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4186 // No commitment_signed so get_event_msg's assert(len == 1) passes
4187 check_added_monitors!(nodes[0], 1);
4189 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4190 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4191 // No commitment_signed so get_event_msg's assert(len == 1) passes
4192 check_added_monitors!(nodes[1], 1);
4194 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4195 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4196 check_added_monitors!(nodes[1], 1);
4198 expect_pending_htlcs_forwardable!(nodes[1]);
4200 let events_5 = nodes[1].node.get_and_clear_pending_events();
4201 assert_eq!(events_5.len(), 1);
4203 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4204 assert_eq!(payment_hash_2, *payment_hash);
4206 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4207 assert!(payment_preimage.is_none());
4208 assert_eq!(payment_secret_2, *payment_secret);
4210 _ => panic!("expected PaymentPurpose::InvoicePayment")
4213 _ => panic!("Unexpected event"),
4216 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4217 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4218 check_added_monitors!(nodes[0], 1);
4220 expect_payment_path_successful!(nodes[0]);
4221 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4224 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4225 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4226 // to avoid our counterparty failing the channel.
4227 let chanmon_cfgs = create_chanmon_cfgs(2);
4228 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4229 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4230 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4232 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4234 let our_payment_hash = if send_partial_mpp {
4235 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4236 // Use the utility function send_payment_along_path to send the payment with MPP data which
4237 // indicates there are more HTLCs coming.
4238 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.
4239 let payment_id = PaymentId([42; 32]);
4240 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
4241 check_added_monitors!(nodes[0], 1);
4242 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4243 assert_eq!(events.len(), 1);
4244 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4245 // hop should *not* yet generate any PaymentReceived event(s).
4246 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4249 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4252 let mut block = Block {
4253 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4256 connect_block(&nodes[0], &block);
4257 connect_block(&nodes[1], &block);
4258 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4259 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4260 block.header.prev_blockhash = block.block_hash();
4261 connect_block(&nodes[0], &block);
4262 connect_block(&nodes[1], &block);
4265 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4267 check_added_monitors!(nodes[1], 1);
4268 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4269 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4270 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4271 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4272 assert!(htlc_timeout_updates.update_fee.is_none());
4274 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4275 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4276 // 100_000 msat as u64, followed by the height at which we failed back above
4277 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4278 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4279 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4283 fn test_htlc_timeout() {
4284 do_test_htlc_timeout(true);
4285 do_test_htlc_timeout(false);
4288 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4289 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4290 let chanmon_cfgs = create_chanmon_cfgs(3);
4291 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4292 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4293 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4294 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4295 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4297 // Make sure all nodes are at the same starting height
4298 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4299 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4300 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4302 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4303 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4305 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4307 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4308 check_added_monitors!(nodes[1], 1);
4310 // Now attempt to route a second payment, which should be placed in the holding cell
4311 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4312 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4313 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4315 check_added_monitors!(nodes[0], 1);
4316 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4317 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4318 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4319 expect_pending_htlcs_forwardable!(nodes[1]);
4321 check_added_monitors!(nodes[1], 0);
4323 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4324 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4325 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4326 connect_blocks(&nodes[1], 1);
4329 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 }]);
4330 check_added_monitors!(nodes[1], 1);
4331 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4332 assert_eq!(fail_commit.len(), 1);
4333 match fail_commit[0] {
4334 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4335 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4336 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4338 _ => unreachable!(),
4340 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4342 let events = nodes[1].node.get_and_clear_pending_events();
4343 assert_eq!(events.len(), 2);
4344 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4345 assert_eq!(*payment_hash, second_payment_hash);
4346 } else { panic!("Unexpected event"); }
4347 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4348 assert_eq!(*payment_hash, second_payment_hash);
4349 } else { panic!("Unexpected event"); }
4354 fn test_holding_cell_htlc_add_timeouts() {
4355 do_test_holding_cell_htlc_add_timeouts(false);
4356 do_test_holding_cell_htlc_add_timeouts(true);
4360 fn test_no_txn_manager_serialize_deserialize() {
4361 let chanmon_cfgs = create_chanmon_cfgs(2);
4362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4364 let logger: test_utils::TestLogger;
4365 let fee_estimator: test_utils::TestFeeEstimator;
4366 let persister: test_utils::TestPersister;
4367 let new_chain_monitor: test_utils::TestChainMonitor;
4368 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4371 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4373 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4375 let nodes_0_serialized = nodes[0].node.encode();
4376 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4377 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4378 .write(&mut chan_0_monitor_serialized).unwrap();
4380 logger = test_utils::TestLogger::new();
4381 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4382 persister = test_utils::TestPersister::new();
4383 let keys_manager = &chanmon_cfgs[0].keys_manager;
4384 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4385 nodes[0].chain_monitor = &new_chain_monitor;
4386 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4387 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4388 &mut chan_0_monitor_read, keys_manager).unwrap();
4389 assert!(chan_0_monitor_read.is_empty());
4391 let mut nodes_0_read = &nodes_0_serialized[..];
4392 let config = UserConfig::default();
4393 let (_, nodes_0_deserialized_tmp) = {
4394 let mut channel_monitors = HashMap::new();
4395 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4396 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4397 default_config: config,
4399 fee_estimator: &fee_estimator,
4400 chain_monitor: nodes[0].chain_monitor,
4401 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4406 nodes_0_deserialized = nodes_0_deserialized_tmp;
4407 assert!(nodes_0_read.is_empty());
4409 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4410 ChannelMonitorUpdateStatus::Completed);
4411 nodes[0].node = &nodes_0_deserialized;
4412 assert_eq!(nodes[0].node.list_channels().len(), 1);
4413 check_added_monitors!(nodes[0], 1);
4415 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4416 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4417 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4418 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4420 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4421 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4422 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4423 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4425 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4426 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4427 for node in nodes.iter() {
4428 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4429 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4430 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4433 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4437 fn test_manager_serialize_deserialize_events() {
4438 // This test makes sure the events field in ChannelManager survives de/serialization
4439 let chanmon_cfgs = create_chanmon_cfgs(2);
4440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4442 let fee_estimator: test_utils::TestFeeEstimator;
4443 let persister: test_utils::TestPersister;
4444 let logger: test_utils::TestLogger;
4445 let new_chain_monitor: test_utils::TestChainMonitor;
4446 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4447 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4449 // Start creating a channel, but stop right before broadcasting the funding transaction
4450 let channel_value = 100000;
4451 let push_msat = 10001;
4452 let a_flags = channelmanager::provided_init_features();
4453 let b_flags = channelmanager::provided_init_features();
4454 let node_a = nodes.remove(0);
4455 let node_b = nodes.remove(0);
4456 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4457 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
4458 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
4460 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4462 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4463 check_added_monitors!(node_a, 0);
4465 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
4467 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4468 assert_eq!(added_monitors.len(), 1);
4469 assert_eq!(added_monitors[0].0, funding_output);
4470 added_monitors.clear();
4473 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4474 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4476 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4477 assert_eq!(added_monitors.len(), 1);
4478 assert_eq!(added_monitors[0].0, funding_output);
4479 added_monitors.clear();
4481 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4486 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4487 let nodes_0_serialized = nodes[0].node.encode();
4488 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4489 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4491 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4492 logger = test_utils::TestLogger::new();
4493 persister = test_utils::TestPersister::new();
4494 let keys_manager = &chanmon_cfgs[0].keys_manager;
4495 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4496 nodes[0].chain_monitor = &new_chain_monitor;
4497 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4498 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4499 &mut chan_0_monitor_read, keys_manager).unwrap();
4500 assert!(chan_0_monitor_read.is_empty());
4502 let mut nodes_0_read = &nodes_0_serialized[..];
4503 let config = UserConfig::default();
4504 let (_, nodes_0_deserialized_tmp) = {
4505 let mut channel_monitors = HashMap::new();
4506 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4507 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4508 default_config: config,
4510 fee_estimator: &fee_estimator,
4511 chain_monitor: nodes[0].chain_monitor,
4512 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4517 nodes_0_deserialized = nodes_0_deserialized_tmp;
4518 assert!(nodes_0_read.is_empty());
4520 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4522 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4523 ChannelMonitorUpdateStatus::Completed);
4524 nodes[0].node = &nodes_0_deserialized;
4526 // After deserializing, make sure the funding_transaction is still held by the channel manager
4527 let events_4 = nodes[0].node.get_and_clear_pending_events();
4528 assert_eq!(events_4.len(), 0);
4529 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4530 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4532 // Make sure the channel is functioning as though the de/serialization never happened
4533 assert_eq!(nodes[0].node.list_channels().len(), 1);
4534 check_added_monitors!(nodes[0], 1);
4536 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4537 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4538 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4539 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4541 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4542 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4543 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4544 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4546 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4547 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4548 for node in nodes.iter() {
4549 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4550 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4551 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4554 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4558 fn test_simple_manager_serialize_deserialize() {
4559 let chanmon_cfgs = create_chanmon_cfgs(2);
4560 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4561 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4562 let logger: test_utils::TestLogger;
4563 let fee_estimator: test_utils::TestFeeEstimator;
4564 let persister: test_utils::TestPersister;
4565 let new_chain_monitor: test_utils::TestChainMonitor;
4566 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4567 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4568 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4570 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4571 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4573 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4575 let nodes_0_serialized = nodes[0].node.encode();
4576 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4577 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4579 logger = test_utils::TestLogger::new();
4580 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4581 persister = test_utils::TestPersister::new();
4582 let keys_manager = &chanmon_cfgs[0].keys_manager;
4583 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4584 nodes[0].chain_monitor = &new_chain_monitor;
4585 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4586 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4587 &mut chan_0_monitor_read, keys_manager).unwrap();
4588 assert!(chan_0_monitor_read.is_empty());
4590 let mut nodes_0_read = &nodes_0_serialized[..];
4591 let (_, nodes_0_deserialized_tmp) = {
4592 let mut channel_monitors = HashMap::new();
4593 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4594 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4595 default_config: UserConfig::default(),
4597 fee_estimator: &fee_estimator,
4598 chain_monitor: nodes[0].chain_monitor,
4599 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4604 nodes_0_deserialized = nodes_0_deserialized_tmp;
4605 assert!(nodes_0_read.is_empty());
4607 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4608 ChannelMonitorUpdateStatus::Completed);
4609 nodes[0].node = &nodes_0_deserialized;
4610 check_added_monitors!(nodes[0], 1);
4612 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4614 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4615 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4619 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4620 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4621 let chanmon_cfgs = create_chanmon_cfgs(4);
4622 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4623 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4624 let logger: test_utils::TestLogger;
4625 let fee_estimator: test_utils::TestFeeEstimator;
4626 let persister: test_utils::TestPersister;
4627 let new_chain_monitor: test_utils::TestChainMonitor;
4628 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4629 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4630 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4631 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4632 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4634 let mut node_0_stale_monitors_serialized = Vec::new();
4635 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4636 let mut writer = test_utils::TestVecWriter(Vec::new());
4637 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4638 node_0_stale_monitors_serialized.push(writer.0);
4641 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4643 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4644 let nodes_0_serialized = nodes[0].node.encode();
4646 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4647 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4648 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4649 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4651 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4653 let mut node_0_monitors_serialized = Vec::new();
4654 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4655 let mut writer = test_utils::TestVecWriter(Vec::new());
4656 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4657 node_0_monitors_serialized.push(writer.0);
4660 logger = test_utils::TestLogger::new();
4661 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4662 persister = test_utils::TestPersister::new();
4663 let keys_manager = &chanmon_cfgs[0].keys_manager;
4664 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4665 nodes[0].chain_monitor = &new_chain_monitor;
4668 let mut node_0_stale_monitors = Vec::new();
4669 for serialized in node_0_stale_monitors_serialized.iter() {
4670 let mut read = &serialized[..];
4671 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4672 assert!(read.is_empty());
4673 node_0_stale_monitors.push(monitor);
4676 let mut node_0_monitors = Vec::new();
4677 for serialized in node_0_monitors_serialized.iter() {
4678 let mut read = &serialized[..];
4679 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4680 assert!(read.is_empty());
4681 node_0_monitors.push(monitor);
4684 let mut nodes_0_read = &nodes_0_serialized[..];
4685 if let Err(msgs::DecodeError::InvalidValue) =
4686 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4687 default_config: UserConfig::default(),
4689 fee_estimator: &fee_estimator,
4690 chain_monitor: nodes[0].chain_monitor,
4691 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4693 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4695 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4698 let mut nodes_0_read = &nodes_0_serialized[..];
4699 let (_, nodes_0_deserialized_tmp) =
4700 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4701 default_config: UserConfig::default(),
4703 fee_estimator: &fee_estimator,
4704 chain_monitor: nodes[0].chain_monitor,
4705 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4707 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4709 nodes_0_deserialized = nodes_0_deserialized_tmp;
4710 assert!(nodes_0_read.is_empty());
4712 { // Channel close should result in a commitment tx
4713 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4714 assert_eq!(txn.len(), 1);
4715 check_spends!(txn[0], funding_tx);
4716 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4719 for monitor in node_0_monitors.drain(..) {
4720 assert_eq!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
4721 ChannelMonitorUpdateStatus::Completed);
4722 check_added_monitors!(nodes[0], 1);
4724 nodes[0].node = &nodes_0_deserialized;
4725 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4727 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4728 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4729 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4730 //... and we can even still claim the payment!
4731 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4733 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4734 let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
4735 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4736 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4737 let mut found_err = false;
4738 for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
4739 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
4741 &ErrorAction::SendErrorMessage { ref msg } => {
4742 assert_eq!(msg.channel_id, channel_id);
4743 assert!(!found_err);
4746 _ => panic!("Unexpected event!"),
4753 macro_rules! check_spendable_outputs {
4754 ($node: expr, $keysinterface: expr) => {
4756 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4757 let mut txn = Vec::new();
4758 let mut all_outputs = Vec::new();
4759 let secp_ctx = Secp256k1::new();
4760 for event in events.drain(..) {
4762 Event::SpendableOutputs { mut outputs } => {
4763 for outp in outputs.drain(..) {
4764 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4765 all_outputs.push(outp);
4768 _ => panic!("Unexpected event"),
4771 if all_outputs.len() > 1 {
4772 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) {
4782 fn test_claim_sizeable_push_msat() {
4783 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4784 let chanmon_cfgs = create_chanmon_cfgs(2);
4785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4789 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4790 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4791 check_closed_broadcast!(nodes[1], true);
4792 check_added_monitors!(nodes[1], 1);
4793 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4794 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4795 assert_eq!(node_txn.len(), 1);
4796 check_spends!(node_txn[0], chan.3);
4797 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
4799 mine_transaction(&nodes[1], &node_txn[0]);
4800 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4802 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4803 assert_eq!(spend_txn.len(), 1);
4804 assert_eq!(spend_txn[0].input.len(), 1);
4805 check_spends!(spend_txn[0], node_txn[0]);
4806 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4810 fn test_claim_on_remote_sizeable_push_msat() {
4811 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4812 // to_remote output is encumbered by a P2WPKH
4813 let chanmon_cfgs = create_chanmon_cfgs(2);
4814 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4815 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4816 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4818 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4819 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4820 check_closed_broadcast!(nodes[0], true);
4821 check_added_monitors!(nodes[0], 1);
4822 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4824 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4825 assert_eq!(node_txn.len(), 1);
4826 check_spends!(node_txn[0], chan.3);
4827 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
4829 mine_transaction(&nodes[1], &node_txn[0]);
4830 check_closed_broadcast!(nodes[1], true);
4831 check_added_monitors!(nodes[1], 1);
4832 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4833 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4835 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4836 assert_eq!(spend_txn.len(), 1);
4837 check_spends!(spend_txn[0], node_txn[0]);
4841 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4842 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4843 // to_remote output is encumbered by a P2WPKH
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 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4851 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4852 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4853 assert_eq!(revoked_local_txn[0].input.len(), 1);
4854 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4856 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4857 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4858 check_closed_broadcast!(nodes[1], true);
4859 check_added_monitors!(nodes[1], 1);
4860 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4862 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4863 mine_transaction(&nodes[1], &node_txn[0]);
4864 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4866 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4867 assert_eq!(spend_txn.len(), 3);
4868 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4869 check_spends!(spend_txn[1], node_txn[0]);
4870 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4874 fn test_static_spendable_outputs_preimage_tx() {
4875 let chanmon_cfgs = create_chanmon_cfgs(2);
4876 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4877 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4878 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4880 // Create some initial channels
4881 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4883 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4885 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4886 assert_eq!(commitment_tx[0].input.len(), 1);
4887 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4889 // Settle A's commitment tx on B's chain
4890 nodes[1].node.claim_funds(payment_preimage);
4891 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4892 check_added_monitors!(nodes[1], 1);
4893 mine_transaction(&nodes[1], &commitment_tx[0]);
4894 check_added_monitors!(nodes[1], 1);
4895 let events = nodes[1].node.get_and_clear_pending_msg_events();
4897 MessageSendEvent::UpdateHTLCs { .. } => {},
4898 _ => panic!("Unexpected event"),
4901 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4902 _ => panic!("Unexepected event"),
4905 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4906 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4907 assert_eq!(node_txn.len(), 3);
4908 check_spends!(node_txn[0], commitment_tx[0]);
4909 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4910 check_spends!(node_txn[1], chan_1.3);
4911 check_spends!(node_txn[2], node_txn[1]);
4913 mine_transaction(&nodes[1], &node_txn[0]);
4914 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4915 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4917 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4918 assert_eq!(spend_txn.len(), 1);
4919 check_spends!(spend_txn[0], node_txn[0]);
4923 fn test_static_spendable_outputs_timeout_tx() {
4924 let chanmon_cfgs = create_chanmon_cfgs(2);
4925 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4926 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4927 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4929 // Create some initial channels
4930 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4932 // Rebalance the network a bit by relaying one payment through all the channels ...
4933 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4935 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4937 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4938 assert_eq!(commitment_tx[0].input.len(), 1);
4939 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4941 // Settle A's commitment tx on B' chain
4942 mine_transaction(&nodes[1], &commitment_tx[0]);
4943 check_added_monitors!(nodes[1], 1);
4944 let events = nodes[1].node.get_and_clear_pending_msg_events();
4946 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4947 _ => panic!("Unexpected event"),
4949 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4951 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4952 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4953 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4954 check_spends!(node_txn[0], chan_1.3.clone());
4955 check_spends!(node_txn[1], commitment_tx[0].clone());
4956 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4958 mine_transaction(&nodes[1], &node_txn[1]);
4959 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4960 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4961 expect_payment_failed!(nodes[1], our_payment_hash, false);
4963 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4964 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4965 check_spends!(spend_txn[0], commitment_tx[0]);
4966 check_spends!(spend_txn[1], node_txn[1]);
4967 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4971 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4972 let chanmon_cfgs = create_chanmon_cfgs(2);
4973 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4974 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4975 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4977 // Create some initial channels
4978 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4980 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4981 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4982 assert_eq!(revoked_local_txn[0].input.len(), 1);
4983 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4985 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4987 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4988 check_closed_broadcast!(nodes[1], true);
4989 check_added_monitors!(nodes[1], 1);
4990 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4992 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4993 assert_eq!(node_txn.len(), 2);
4994 assert_eq!(node_txn[0].input.len(), 2);
4995 check_spends!(node_txn[0], revoked_local_txn[0]);
4997 mine_transaction(&nodes[1], &node_txn[0]);
4998 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5000 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5001 assert_eq!(spend_txn.len(), 1);
5002 check_spends!(spend_txn[0], node_txn[0]);
5006 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5007 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5008 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5009 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5010 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5011 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5013 // Create some initial channels
5014 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5016 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5017 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5018 assert_eq!(revoked_local_txn[0].input.len(), 1);
5019 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5021 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5023 // A will generate HTLC-Timeout from revoked commitment tx
5024 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5025 check_closed_broadcast!(nodes[0], true);
5026 check_added_monitors!(nodes[0], 1);
5027 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5028 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5030 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5031 assert_eq!(revoked_htlc_txn.len(), 2);
5032 check_spends!(revoked_htlc_txn[0], chan_1.3);
5033 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5034 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5035 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5036 assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
5038 // B will generate justice tx from A's revoked commitment/HTLC tx
5039 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5040 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5041 check_closed_broadcast!(nodes[1], true);
5042 check_added_monitors!(nodes[1], 1);
5043 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5045 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5046 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5047 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5048 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5049 // transactions next...
5050 assert_eq!(node_txn[0].input.len(), 3);
5051 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5053 assert_eq!(node_txn[1].input.len(), 2);
5054 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5055 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5056 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5058 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5059 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5062 assert_eq!(node_txn[2].input.len(), 1);
5063 check_spends!(node_txn[2], chan_1.3);
5065 mine_transaction(&nodes[1], &node_txn[1]);
5066 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5068 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5069 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5070 assert_eq!(spend_txn.len(), 1);
5071 assert_eq!(spend_txn[0].input.len(), 1);
5072 check_spends!(spend_txn[0], node_txn[1]);
5076 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5077 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5078 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5081 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5083 // Create some initial channels
5084 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5086 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5087 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5088 assert_eq!(revoked_local_txn[0].input.len(), 1);
5089 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5091 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5092 assert_eq!(revoked_local_txn[0].output.len(), 2);
5094 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5096 // B will generate HTLC-Success from revoked commitment tx
5097 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5098 check_closed_broadcast!(nodes[1], true);
5099 check_added_monitors!(nodes[1], 1);
5100 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5101 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5103 assert_eq!(revoked_htlc_txn.len(), 2);
5104 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5105 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5106 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5108 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5109 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5110 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5112 // A will generate justice tx from B's revoked commitment/HTLC tx
5113 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5114 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5115 check_closed_broadcast!(nodes[0], true);
5116 check_added_monitors!(nodes[0], 1);
5117 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5119 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5120 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5122 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5123 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5124 // transactions next...
5125 assert_eq!(node_txn[0].input.len(), 2);
5126 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5127 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5128 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5130 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5131 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5134 assert_eq!(node_txn[1].input.len(), 1);
5135 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5137 check_spends!(node_txn[2], chan_1.3);
5139 mine_transaction(&nodes[0], &node_txn[1]);
5140 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5142 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5143 // didn't try to generate any new transactions.
5145 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5146 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5147 assert_eq!(spend_txn.len(), 3);
5148 assert_eq!(spend_txn[0].input.len(), 1);
5149 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5150 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5151 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5152 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5156 fn test_onchain_to_onchain_claim() {
5157 // Test that in case of channel closure, we detect the state of output and claim HTLC
5158 // on downstream peer's remote commitment tx.
5159 // First, have C claim an HTLC against its own latest commitment transaction.
5160 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5162 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5165 let chanmon_cfgs = create_chanmon_cfgs(3);
5166 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5167 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5168 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5170 // Create some initial channels
5171 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5172 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5174 // Ensure all nodes are at the same height
5175 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5176 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5177 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5178 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5180 // Rebalance the network a bit by relaying one payment through all the channels ...
5181 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5182 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5184 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5185 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5186 check_spends!(commitment_tx[0], chan_2.3);
5187 nodes[2].node.claim_funds(payment_preimage);
5188 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5189 check_added_monitors!(nodes[2], 1);
5190 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5191 assert!(updates.update_add_htlcs.is_empty());
5192 assert!(updates.update_fail_htlcs.is_empty());
5193 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5194 assert!(updates.update_fail_malformed_htlcs.is_empty());
5196 mine_transaction(&nodes[2], &commitment_tx[0]);
5197 check_closed_broadcast!(nodes[2], true);
5198 check_added_monitors!(nodes[2], 1);
5199 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5201 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5202 assert_eq!(c_txn.len(), 3);
5203 assert_eq!(c_txn[0], c_txn[2]);
5204 assert_eq!(commitment_tx[0], c_txn[1]);
5205 check_spends!(c_txn[1], chan_2.3);
5206 check_spends!(c_txn[2], c_txn[1]);
5207 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5208 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5209 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5210 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5212 // 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
5213 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5214 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5215 check_added_monitors!(nodes[1], 1);
5216 let events = nodes[1].node.get_and_clear_pending_events();
5217 assert_eq!(events.len(), 2);
5219 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5220 _ => panic!("Unexpected event"),
5223 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5224 assert_eq!(fee_earned_msat, Some(1000));
5225 assert_eq!(prev_channel_id, Some(chan_1.2));
5226 assert_eq!(claim_from_onchain_tx, true);
5227 assert_eq!(next_channel_id, Some(chan_2.2));
5229 _ => panic!("Unexpected event"),
5232 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5233 // ChannelMonitor: claim tx
5234 assert_eq!(b_txn.len(), 1);
5235 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5238 check_added_monitors!(nodes[1], 1);
5239 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5240 assert_eq!(msg_events.len(), 3);
5241 match msg_events[0] {
5242 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5243 _ => panic!("Unexpected event"),
5245 match msg_events[1] {
5246 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5247 _ => panic!("Unexpected event"),
5249 match msg_events[2] {
5250 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, .. } } => {
5251 assert!(update_add_htlcs.is_empty());
5252 assert!(update_fail_htlcs.is_empty());
5253 assert_eq!(update_fulfill_htlcs.len(), 1);
5254 assert!(update_fail_malformed_htlcs.is_empty());
5255 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5257 _ => panic!("Unexpected event"),
5259 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5260 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5261 mine_transaction(&nodes[1], &commitment_tx[0]);
5262 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5263 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5264 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5265 assert_eq!(b_txn.len(), 3);
5266 check_spends!(b_txn[1], chan_1.3);
5267 check_spends!(b_txn[2], b_txn[1]);
5268 check_spends!(b_txn[0], commitment_tx[0]);
5269 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5270 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5271 assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5273 check_closed_broadcast!(nodes[1], true);
5274 check_added_monitors!(nodes[1], 1);
5278 fn test_duplicate_payment_hash_one_failure_one_success() {
5279 // Topology : A --> B --> C --> D
5280 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5281 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5282 // we forward one of the payments onwards to D.
5283 let chanmon_cfgs = create_chanmon_cfgs(4);
5284 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5285 // When this test was written, the default base fee floated based on the HTLC count.
5286 // It is now fixed, so we simply set the fee to the expected value here.
5287 let mut config = test_default_channel_config();
5288 config.channel_config.forwarding_fee_base_msat = 196;
5289 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5290 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5291 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5293 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5294 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5295 create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5297 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5298 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5299 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5300 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5301 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5303 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5305 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5306 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5307 // script push size limit so that the below script length checks match
5308 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5309 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5310 .with_features(channelmanager::provided_invoice_features());
5311 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5312 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5314 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5315 assert_eq!(commitment_txn[0].input.len(), 1);
5316 check_spends!(commitment_txn[0], chan_2.3);
5318 mine_transaction(&nodes[1], &commitment_txn[0]);
5319 check_closed_broadcast!(nodes[1], true);
5320 check_added_monitors!(nodes[1], 1);
5321 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5322 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5324 let htlc_timeout_tx;
5325 { // Extract one of the two HTLC-Timeout transaction
5326 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5327 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5328 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5329 check_spends!(node_txn[0], chan_2.3);
5331 check_spends!(node_txn[1], commitment_txn[0]);
5332 assert_eq!(node_txn[1].input.len(), 1);
5334 if node_txn.len() > 3 {
5335 check_spends!(node_txn[2], commitment_txn[0]);
5336 assert_eq!(node_txn[2].input.len(), 1);
5337 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5339 check_spends!(node_txn[3], commitment_txn[0]);
5340 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5342 check_spends!(node_txn[2], commitment_txn[0]);
5343 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5346 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5347 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5348 if node_txn.len() > 3 {
5349 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5351 htlc_timeout_tx = node_txn[1].clone();
5354 nodes[2].node.claim_funds(our_payment_preimage);
5355 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5357 mine_transaction(&nodes[2], &commitment_txn[0]);
5358 check_added_monitors!(nodes[2], 2);
5359 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5360 let events = nodes[2].node.get_and_clear_pending_msg_events();
5362 MessageSendEvent::UpdateHTLCs { .. } => {},
5363 _ => panic!("Unexpected event"),
5366 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5367 _ => panic!("Unexepected event"),
5369 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5370 assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
5371 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5372 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5373 assert_eq!(htlc_success_txn[0].input.len(), 1);
5374 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5375 assert_eq!(htlc_success_txn[1].input.len(), 1);
5376 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5377 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5378 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5379 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5380 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5381 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5383 mine_transaction(&nodes[1], &htlc_timeout_tx);
5384 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5385 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 }]);
5386 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5387 assert!(htlc_updates.update_add_htlcs.is_empty());
5388 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5389 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5390 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5391 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5392 check_added_monitors!(nodes[1], 1);
5394 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5395 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5397 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5399 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5401 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5402 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5403 // and nodes[2] fee) is rounded down and then claimed in full.
5404 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5405 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5406 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5407 assert!(updates.update_add_htlcs.is_empty());
5408 assert!(updates.update_fail_htlcs.is_empty());
5409 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5410 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5411 assert!(updates.update_fail_malformed_htlcs.is_empty());
5412 check_added_monitors!(nodes[1], 1);
5414 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5415 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5417 let events = nodes[0].node.get_and_clear_pending_events();
5419 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5420 assert_eq!(*payment_preimage, our_payment_preimage);
5421 assert_eq!(*payment_hash, duplicate_payment_hash);
5423 _ => panic!("Unexpected event"),
5428 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5429 let chanmon_cfgs = create_chanmon_cfgs(2);
5430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5434 // Create some initial channels
5435 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5437 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5438 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5439 assert_eq!(local_txn.len(), 1);
5440 assert_eq!(local_txn[0].input.len(), 1);
5441 check_spends!(local_txn[0], chan_1.3);
5443 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5444 nodes[1].node.claim_funds(payment_preimage);
5445 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5446 check_added_monitors!(nodes[1], 1);
5448 mine_transaction(&nodes[1], &local_txn[0]);
5449 check_added_monitors!(nodes[1], 1);
5450 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5451 let events = nodes[1].node.get_and_clear_pending_msg_events();
5453 MessageSendEvent::UpdateHTLCs { .. } => {},
5454 _ => panic!("Unexpected event"),
5457 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5458 _ => panic!("Unexepected event"),
5461 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5462 assert_eq!(node_txn.len(), 3);
5463 assert_eq!(node_txn[0], node_txn[2]);
5464 assert_eq!(node_txn[1], local_txn[0]);
5465 assert_eq!(node_txn[0].input.len(), 1);
5466 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5467 check_spends!(node_txn[0], local_txn[0]);
5471 mine_transaction(&nodes[1], &node_tx);
5472 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5474 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5475 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5476 assert_eq!(spend_txn.len(), 1);
5477 assert_eq!(spend_txn[0].input.len(), 1);
5478 check_spends!(spend_txn[0], node_tx);
5479 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5482 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5483 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5484 // unrevoked commitment transaction.
5485 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5486 // a remote RAA before they could be failed backwards (and combinations thereof).
5487 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5488 // use the same payment hashes.
5489 // Thus, we use a six-node network:
5494 // And test where C fails back to A/B when D announces its latest commitment transaction
5495 let chanmon_cfgs = create_chanmon_cfgs(6);
5496 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5497 // When this test was written, the default base fee floated based on the HTLC count.
5498 // It is now fixed, so we simply set the fee to the expected value here.
5499 let mut config = test_default_channel_config();
5500 config.channel_config.forwarding_fee_base_msat = 196;
5501 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5502 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5503 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5505 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5506 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5507 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5508 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5509 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5511 // Rebalance and check output sanity...
5512 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5513 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5514 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5516 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5518 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
5520 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
5521 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5523 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200).unwrap()); // not added < dust limit + HTLC tx fee
5525 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200).unwrap()); // not added < dust limit + HTLC tx fee
5527 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5529 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5530 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5532 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200).unwrap());
5534 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200).unwrap());
5537 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5539 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5540 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200).unwrap()); // not added < dust limit + HTLC tx fee
5543 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
5545 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5546 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200).unwrap());
5548 // Double-check that six of the new HTLC were added
5549 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5550 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5551 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5552 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5554 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5555 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5556 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5557 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5558 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5559 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5560 check_added_monitors!(nodes[4], 0);
5562 let failed_destinations = vec![
5563 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5564 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5565 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5566 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5568 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5569 check_added_monitors!(nodes[4], 1);
5571 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5572 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5573 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5574 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5575 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5576 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5578 // Fail 3rd below-dust and 7th above-dust HTLCs
5579 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5580 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5581 check_added_monitors!(nodes[5], 0);
5583 let failed_destinations_2 = vec![
5584 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5585 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5587 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5588 check_added_monitors!(nodes[5], 1);
5590 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5591 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5592 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5593 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5595 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5597 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5598 let failed_destinations_3 = vec![
5599 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5600 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5601 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5602 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5603 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5604 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5606 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5607 check_added_monitors!(nodes[3], 1);
5608 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5609 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5610 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5611 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5612 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5613 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5614 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5615 if deliver_last_raa {
5616 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5618 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5621 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5622 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5623 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5624 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5626 // We now broadcast the latest commitment transaction, which *should* result in failures for
5627 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5628 // the non-broadcast above-dust HTLCs.
5630 // Alternatively, we may broadcast the previous commitment transaction, which should only
5631 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5632 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5634 if announce_latest {
5635 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5637 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5639 let events = nodes[2].node.get_and_clear_pending_events();
5640 let close_event = if deliver_last_raa {
5641 assert_eq!(events.len(), 2 + 6);
5642 events.last().clone().unwrap()
5644 assert_eq!(events.len(), 1);
5645 events.last().clone().unwrap()
5648 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5649 _ => panic!("Unexpected event"),
5652 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5653 check_closed_broadcast!(nodes[2], true);
5654 if deliver_last_raa {
5655 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5657 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();
5658 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5660 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5661 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5663 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5666 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5668 check_added_monitors!(nodes[2], 3);
5670 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5671 assert_eq!(cs_msgs.len(), 2);
5672 let mut a_done = false;
5673 for msg in cs_msgs {
5675 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5676 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5677 // should be failed-backwards here.
5678 let target = if *node_id == nodes[0].node.get_our_node_id() {
5679 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5680 for htlc in &updates.update_fail_htlcs {
5681 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 });
5683 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5688 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5689 for htlc in &updates.update_fail_htlcs {
5690 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5692 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5693 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5696 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5697 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5698 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5699 if announce_latest {
5700 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5701 if *node_id == nodes[0].node.get_our_node_id() {
5702 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5705 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5707 _ => panic!("Unexpected event"),
5711 let as_events = nodes[0].node.get_and_clear_pending_events();
5712 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5713 let mut as_failds = HashSet::new();
5714 let mut as_updates = 0;
5715 for event in as_events.iter() {
5716 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5717 assert!(as_failds.insert(*payment_hash));
5718 if *payment_hash != payment_hash_2 {
5719 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5721 assert!(!payment_failed_permanently);
5723 if network_update.is_some() {
5726 } else { panic!("Unexpected event"); }
5728 assert!(as_failds.contains(&payment_hash_1));
5729 assert!(as_failds.contains(&payment_hash_2));
5730 if announce_latest {
5731 assert!(as_failds.contains(&payment_hash_3));
5732 assert!(as_failds.contains(&payment_hash_5));
5734 assert!(as_failds.contains(&payment_hash_6));
5736 let bs_events = nodes[1].node.get_and_clear_pending_events();
5737 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5738 let mut bs_failds = HashSet::new();
5739 let mut bs_updates = 0;
5740 for event in bs_events.iter() {
5741 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5742 assert!(bs_failds.insert(*payment_hash));
5743 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5744 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5746 assert!(!payment_failed_permanently);
5748 if network_update.is_some() {
5751 } else { panic!("Unexpected event"); }
5753 assert!(bs_failds.contains(&payment_hash_1));
5754 assert!(bs_failds.contains(&payment_hash_2));
5755 if announce_latest {
5756 assert!(bs_failds.contains(&payment_hash_4));
5758 assert!(bs_failds.contains(&payment_hash_5));
5760 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5761 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5762 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5763 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5764 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5765 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5769 fn test_fail_backwards_latest_remote_announce_a() {
5770 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5774 fn test_fail_backwards_latest_remote_announce_b() {
5775 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5779 fn test_fail_backwards_previous_remote_announce() {
5780 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5781 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5782 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5786 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5787 let chanmon_cfgs = create_chanmon_cfgs(2);
5788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5790 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5792 // Create some initial channels
5793 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5795 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5796 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5797 assert_eq!(local_txn[0].input.len(), 1);
5798 check_spends!(local_txn[0], chan_1.3);
5800 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5801 mine_transaction(&nodes[0], &local_txn[0]);
5802 check_closed_broadcast!(nodes[0], true);
5803 check_added_monitors!(nodes[0], 1);
5804 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5805 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5807 let htlc_timeout = {
5808 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5809 assert_eq!(node_txn.len(), 2);
5810 check_spends!(node_txn[0], chan_1.3);
5811 assert_eq!(node_txn[1].input.len(), 1);
5812 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5813 check_spends!(node_txn[1], local_txn[0]);
5817 mine_transaction(&nodes[0], &htlc_timeout);
5818 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5819 expect_payment_failed!(nodes[0], our_payment_hash, false);
5821 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5822 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5823 assert_eq!(spend_txn.len(), 3);
5824 check_spends!(spend_txn[0], local_txn[0]);
5825 assert_eq!(spend_txn[1].input.len(), 1);
5826 check_spends!(spend_txn[1], htlc_timeout);
5827 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5828 assert_eq!(spend_txn[2].input.len(), 2);
5829 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5830 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5831 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5835 fn test_key_derivation_params() {
5836 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5837 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5838 // let us re-derive the channel key set to then derive a delayed_payment_key.
5840 let chanmon_cfgs = create_chanmon_cfgs(3);
5842 // We manually create the node configuration to backup the seed.
5843 let seed = [42; 32];
5844 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5845 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);
5846 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5847 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, features: channelmanager::provided_init_features() };
5848 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5849 node_cfgs.remove(0);
5850 node_cfgs.insert(0, node);
5852 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5853 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5855 // Create some initial channels
5856 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5858 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5859 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5860 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5862 // Ensure all nodes are at the same height
5863 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5864 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5865 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5866 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5868 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5869 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5870 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5871 assert_eq!(local_txn_1[0].input.len(), 1);
5872 check_spends!(local_txn_1[0], chan_1.3);
5874 // We check funding pubkey are unique
5875 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]));
5876 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]));
5877 if from_0_funding_key_0 == from_1_funding_key_0
5878 || from_0_funding_key_0 == from_1_funding_key_1
5879 || from_0_funding_key_1 == from_1_funding_key_0
5880 || from_0_funding_key_1 == from_1_funding_key_1 {
5881 panic!("Funding pubkeys aren't unique");
5884 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5885 mine_transaction(&nodes[0], &local_txn_1[0]);
5886 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5887 check_closed_broadcast!(nodes[0], true);
5888 check_added_monitors!(nodes[0], 1);
5889 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5891 let htlc_timeout = {
5892 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5893 assert_eq!(node_txn[1].input.len(), 1);
5894 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5895 check_spends!(node_txn[1], local_txn_1[0]);
5899 mine_transaction(&nodes[0], &htlc_timeout);
5900 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5901 expect_payment_failed!(nodes[0], our_payment_hash, false);
5903 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5904 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5905 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5906 assert_eq!(spend_txn.len(), 3);
5907 check_spends!(spend_txn[0], local_txn_1[0]);
5908 assert_eq!(spend_txn[1].input.len(), 1);
5909 check_spends!(spend_txn[1], htlc_timeout);
5910 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5911 assert_eq!(spend_txn[2].input.len(), 2);
5912 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5913 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5914 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5918 fn test_static_output_closing_tx() {
5919 let chanmon_cfgs = create_chanmon_cfgs(2);
5920 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5921 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5922 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5924 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5926 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5927 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5929 mine_transaction(&nodes[0], &closing_tx);
5930 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5931 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5933 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5934 assert_eq!(spend_txn.len(), 1);
5935 check_spends!(spend_txn[0], closing_tx);
5937 mine_transaction(&nodes[1], &closing_tx);
5938 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5939 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5941 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5942 assert_eq!(spend_txn.len(), 1);
5943 check_spends!(spend_txn[0], closing_tx);
5946 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5947 let chanmon_cfgs = create_chanmon_cfgs(2);
5948 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5949 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5950 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5951 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5953 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5955 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5956 // present in B's local commitment transaction, but none of A's commitment transactions.
5957 nodes[1].node.claim_funds(payment_preimage);
5958 check_added_monitors!(nodes[1], 1);
5959 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5961 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5962 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5963 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5965 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5966 check_added_monitors!(nodes[0], 1);
5967 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5968 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5969 check_added_monitors!(nodes[1], 1);
5971 let starting_block = nodes[1].best_block_info();
5972 let mut block = Block {
5973 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5976 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5977 connect_block(&nodes[1], &block);
5978 block.header.prev_blockhash = block.block_hash();
5980 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5981 check_closed_broadcast!(nodes[1], true);
5982 check_added_monitors!(nodes[1], 1);
5983 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5986 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5987 let chanmon_cfgs = create_chanmon_cfgs(2);
5988 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5989 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5990 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5991 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5993 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5994 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5995 check_added_monitors!(nodes[0], 1);
5997 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5999 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
6000 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
6001 // to "time out" the HTLC.
6003 let starting_block = nodes[1].best_block_info();
6004 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
6006 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
6007 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
6008 header.prev_blockhash = header.block_hash();
6010 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6011 check_closed_broadcast!(nodes[0], true);
6012 check_added_monitors!(nodes[0], 1);
6013 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6016 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6017 let chanmon_cfgs = create_chanmon_cfgs(3);
6018 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6019 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6020 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6021 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6023 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6024 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6025 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6026 // actually revoked.
6027 let htlc_value = if use_dust { 50000 } else { 3000000 };
6028 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6029 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6030 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6031 check_added_monitors!(nodes[1], 1);
6033 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6034 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6035 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6036 check_added_monitors!(nodes[0], 1);
6037 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6038 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6039 check_added_monitors!(nodes[1], 1);
6040 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6041 check_added_monitors!(nodes[1], 1);
6042 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6044 if check_revoke_no_close {
6045 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6046 check_added_monitors!(nodes[0], 1);
6049 let starting_block = nodes[1].best_block_info();
6050 let mut block = Block {
6051 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
6054 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6055 connect_block(&nodes[0], &block);
6056 block.header.prev_blockhash = block.block_hash();
6058 if !check_revoke_no_close {
6059 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6060 check_closed_broadcast!(nodes[0], true);
6061 check_added_monitors!(nodes[0], 1);
6062 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6064 let events = nodes[0].node.get_and_clear_pending_events();
6065 assert_eq!(events.len(), 2);
6066 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6067 assert_eq!(*payment_hash, our_payment_hash);
6068 } else { panic!("Unexpected event"); }
6069 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6070 assert_eq!(*payment_hash, our_payment_hash);
6071 } else { panic!("Unexpected event"); }
6075 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6076 // There are only a few cases to test here:
6077 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6078 // broadcastable commitment transactions result in channel closure,
6079 // * its included in an unrevoked-but-previous remote commitment transaction,
6080 // * its included in the latest remote or local commitment transactions.
6081 // We test each of the three possible commitment transactions individually and use both dust and
6083 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6084 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6085 // tested for at least one of the cases in other tests.
6087 fn htlc_claim_single_commitment_only_a() {
6088 do_htlc_claim_local_commitment_only(true);
6089 do_htlc_claim_local_commitment_only(false);
6091 do_htlc_claim_current_remote_commitment_only(true);
6092 do_htlc_claim_current_remote_commitment_only(false);
6096 fn htlc_claim_single_commitment_only_b() {
6097 do_htlc_claim_previous_remote_commitment_only(true, false);
6098 do_htlc_claim_previous_remote_commitment_only(false, false);
6099 do_htlc_claim_previous_remote_commitment_only(true, true);
6100 do_htlc_claim_previous_remote_commitment_only(false, true);
6105 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6106 let chanmon_cfgs = create_chanmon_cfgs(2);
6107 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6108 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6109 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6110 // Force duplicate randomness for every get-random call
6111 for node in nodes.iter() {
6112 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6115 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6116 let channel_value_satoshis=10000;
6117 let push_msat=10001;
6118 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6119 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6120 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6121 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6123 // Create a second channel with the same random values. This used to panic due to a colliding
6124 // channel_id, but now panics due to a colliding outbound SCID alias.
6125 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6129 fn bolt2_open_channel_sending_node_checks_part2() {
6130 let chanmon_cfgs = create_chanmon_cfgs(2);
6131 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6132 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6133 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6135 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6136 let channel_value_satoshis=2^24;
6137 let push_msat=10001;
6138 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6140 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6141 let channel_value_satoshis=10000;
6142 // Test when push_msat is equal to 1000 * funding_satoshis.
6143 let push_msat=1000*channel_value_satoshis+1;
6144 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6146 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6147 let channel_value_satoshis=10000;
6148 let push_msat=10001;
6149 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
6150 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6151 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6153 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6154 // 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
6155 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6157 // 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.
6158 assert!(BREAKDOWN_TIMEOUT>0);
6159 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6161 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6162 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6163 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6165 // 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.
6166 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6167 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6168 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6169 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6170 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6174 fn bolt2_open_channel_sane_dust_limit() {
6175 let chanmon_cfgs = create_chanmon_cfgs(2);
6176 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6177 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6178 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6180 let channel_value_satoshis=1000000;
6181 let push_msat=10001;
6182 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6183 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6184 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6185 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6187 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6188 let events = nodes[1].node.get_and_clear_pending_msg_events();
6189 let err_msg = match events[0] {
6190 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6193 _ => panic!("Unexpected event"),
6195 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6198 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6199 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6200 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6201 // is no longer affordable once it's freed.
6203 fn test_fail_holding_cell_htlc_upon_free() {
6204 let chanmon_cfgs = create_chanmon_cfgs(2);
6205 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6206 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6207 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6208 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6210 // First nodes[0] generates an update_fee, setting the channel's
6211 // pending_update_fee.
6213 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6214 *feerate_lock += 20;
6216 nodes[0].node.timer_tick_occurred();
6217 check_added_monitors!(nodes[0], 1);
6219 let events = nodes[0].node.get_and_clear_pending_msg_events();
6220 assert_eq!(events.len(), 1);
6221 let (update_msg, commitment_signed) = match events[0] {
6222 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6223 (update_fee.as_ref(), commitment_signed)
6225 _ => panic!("Unexpected event"),
6228 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6230 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6231 let channel_reserve = chan_stat.channel_reserve_msat;
6232 let feerate = get_feerate!(nodes[0], chan.2);
6233 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6235 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6236 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6237 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6239 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6240 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6241 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6242 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6244 // Flush the pending fee update.
6245 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6246 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6247 check_added_monitors!(nodes[1], 1);
6248 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6249 check_added_monitors!(nodes[0], 1);
6251 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6252 // HTLC, but now that the fee has been raised the payment will now fail, causing
6253 // us to surface its failure to the user.
6254 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6255 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6256 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);
6257 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 {}",
6258 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6259 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6261 // Check that the payment failed to be sent out.
6262 let events = nodes[0].node.get_and_clear_pending_events();
6263 assert_eq!(events.len(), 1);
6265 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6266 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6267 assert_eq!(our_payment_hash.clone(), *payment_hash);
6268 assert_eq!(*payment_failed_permanently, false);
6269 assert_eq!(*all_paths_failed, true);
6270 assert_eq!(*network_update, None);
6271 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
6273 _ => panic!("Unexpected event"),
6277 // Test that if multiple HTLCs are released from the holding cell and one is
6278 // valid but the other is no longer valid upon release, the valid HTLC can be
6279 // successfully completed while the other one fails as expected.
6281 fn test_free_and_fail_holding_cell_htlcs() {
6282 let chanmon_cfgs = create_chanmon_cfgs(2);
6283 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6284 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6285 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6286 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6288 // First nodes[0] generates an update_fee, setting the channel's
6289 // pending_update_fee.
6291 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6292 *feerate_lock += 200;
6294 nodes[0].node.timer_tick_occurred();
6295 check_added_monitors!(nodes[0], 1);
6297 let events = nodes[0].node.get_and_clear_pending_msg_events();
6298 assert_eq!(events.len(), 1);
6299 let (update_msg, commitment_signed) = match events[0] {
6300 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6301 (update_fee.as_ref(), commitment_signed)
6303 _ => panic!("Unexpected event"),
6306 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6308 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6309 let channel_reserve = chan_stat.channel_reserve_msat;
6310 let feerate = get_feerate!(nodes[0], chan.2);
6311 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6313 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6315 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6316 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6317 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6319 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6320 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6321 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6322 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6323 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6324 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6325 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6327 // Flush the pending fee update.
6328 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6329 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6330 check_added_monitors!(nodes[1], 1);
6331 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6332 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6333 check_added_monitors!(nodes[0], 2);
6335 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6336 // but now that the fee has been raised the second payment will now fail, causing us
6337 // to surface its failure to the user. The first payment should succeed.
6338 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6339 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6340 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);
6341 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 {}",
6342 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6343 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6345 // Check that the second payment failed to be sent out.
6346 let events = nodes[0].node.get_and_clear_pending_events();
6347 assert_eq!(events.len(), 1);
6349 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6350 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6351 assert_eq!(payment_hash_2.clone(), *payment_hash);
6352 assert_eq!(*payment_failed_permanently, false);
6353 assert_eq!(*all_paths_failed, true);
6354 assert_eq!(*network_update, None);
6355 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
6357 _ => panic!("Unexpected event"),
6360 // Complete the first payment and the RAA from the fee update.
6361 let (payment_event, send_raa_event) = {
6362 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6363 assert_eq!(msgs.len(), 2);
6364 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6366 let raa = match send_raa_event {
6367 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6368 _ => panic!("Unexpected event"),
6370 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6371 check_added_monitors!(nodes[1], 1);
6372 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6373 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6374 let events = nodes[1].node.get_and_clear_pending_events();
6375 assert_eq!(events.len(), 1);
6377 Event::PendingHTLCsForwardable { .. } => {},
6378 _ => panic!("Unexpected event"),
6380 nodes[1].node.process_pending_htlc_forwards();
6381 let events = nodes[1].node.get_and_clear_pending_events();
6382 assert_eq!(events.len(), 1);
6384 Event::PaymentReceived { .. } => {},
6385 _ => panic!("Unexpected event"),
6387 nodes[1].node.claim_funds(payment_preimage_1);
6388 check_added_monitors!(nodes[1], 1);
6389 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6391 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6392 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6393 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6394 expect_payment_sent!(nodes[0], payment_preimage_1);
6397 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6398 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6399 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6402 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6403 let chanmon_cfgs = create_chanmon_cfgs(3);
6404 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6405 // When this test was written, the default base fee floated based on the HTLC count.
6406 // It is now fixed, so we simply set the fee to the expected value here.
6407 let mut config = test_default_channel_config();
6408 config.channel_config.forwarding_fee_base_msat = 196;
6409 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6410 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6411 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6412 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6414 // First nodes[1] generates an update_fee, setting the channel's
6415 // pending_update_fee.
6417 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6418 *feerate_lock += 20;
6420 nodes[1].node.timer_tick_occurred();
6421 check_added_monitors!(nodes[1], 1);
6423 let events = nodes[1].node.get_and_clear_pending_msg_events();
6424 assert_eq!(events.len(), 1);
6425 let (update_msg, commitment_signed) = match events[0] {
6426 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6427 (update_fee.as_ref(), commitment_signed)
6429 _ => panic!("Unexpected event"),
6432 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6434 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6435 let channel_reserve = chan_stat.channel_reserve_msat;
6436 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6437 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6439 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6441 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6442 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6443 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6444 let payment_event = {
6445 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6446 check_added_monitors!(nodes[0], 1);
6448 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6449 assert_eq!(events.len(), 1);
6451 SendEvent::from_event(events.remove(0))
6453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6454 check_added_monitors!(nodes[1], 0);
6455 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6456 expect_pending_htlcs_forwardable!(nodes[1]);
6458 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6459 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6461 // Flush the pending fee update.
6462 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6463 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6464 check_added_monitors!(nodes[2], 1);
6465 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6466 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6467 check_added_monitors!(nodes[1], 2);
6469 // A final RAA message is generated to finalize the fee update.
6470 let events = nodes[1].node.get_and_clear_pending_msg_events();
6471 assert_eq!(events.len(), 1);
6473 let raa_msg = match &events[0] {
6474 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6477 _ => panic!("Unexpected event"),
6480 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6481 check_added_monitors!(nodes[2], 1);
6482 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6484 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6485 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6486 assert_eq!(process_htlc_forwards_event.len(), 2);
6487 match &process_htlc_forwards_event[0] {
6488 &Event::PendingHTLCsForwardable { .. } => {},
6489 _ => panic!("Unexpected event"),
6492 // In response, we call ChannelManager's process_pending_htlc_forwards
6493 nodes[1].node.process_pending_htlc_forwards();
6494 check_added_monitors!(nodes[1], 1);
6496 // This causes the HTLC to be failed backwards.
6497 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6498 assert_eq!(fail_event.len(), 1);
6499 let (fail_msg, commitment_signed) = match &fail_event[0] {
6500 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6501 assert_eq!(updates.update_add_htlcs.len(), 0);
6502 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6503 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6504 assert_eq!(updates.update_fail_htlcs.len(), 1);
6505 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6507 _ => panic!("Unexpected event"),
6510 // Pass the failure messages back to nodes[0].
6511 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6512 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6514 // Complete the HTLC failure+removal process.
6515 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6516 check_added_monitors!(nodes[0], 1);
6517 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6518 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6519 check_added_monitors!(nodes[1], 2);
6520 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6521 assert_eq!(final_raa_event.len(), 1);
6522 let raa = match &final_raa_event[0] {
6523 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6524 _ => panic!("Unexpected event"),
6526 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6527 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6528 check_added_monitors!(nodes[0], 1);
6531 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6532 // 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.
6533 //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.
6536 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6537 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6538 let chanmon_cfgs = create_chanmon_cfgs(2);
6539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6541 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6542 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6544 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6545 route.paths[0][0].fee_msat = 100;
6547 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6548 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6549 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6550 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6554 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6555 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6556 let chanmon_cfgs = create_chanmon_cfgs(2);
6557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6559 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6560 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6562 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6563 route.paths[0][0].fee_msat = 0;
6564 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6565 assert_eq!(err, "Cannot send 0-msat HTLC"));
6567 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6568 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6572 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6573 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6574 let chanmon_cfgs = create_chanmon_cfgs(2);
6575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6577 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6578 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6580 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6581 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6582 check_added_monitors!(nodes[0], 1);
6583 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6584 updates.update_add_htlcs[0].amount_msat = 0;
6586 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6587 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6588 check_closed_broadcast!(nodes[1], true).unwrap();
6589 check_added_monitors!(nodes[1], 1);
6590 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6594 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6595 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6596 //It is enforced when constructing a route.
6597 let chanmon_cfgs = create_chanmon_cfgs(2);
6598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6600 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6601 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6603 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6604 .with_features(channelmanager::provided_invoice_features());
6605 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6606 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6607 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6608 assert_eq!(err, &"Channel CLTV overflowed?"));
6612 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6613 //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.
6614 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6615 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6616 let chanmon_cfgs = create_chanmon_cfgs(2);
6617 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6618 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6619 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6620 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6621 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6623 for i in 0..max_accepted_htlcs {
6624 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6625 let payment_event = {
6626 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6627 check_added_monitors!(nodes[0], 1);
6629 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6630 assert_eq!(events.len(), 1);
6631 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6632 assert_eq!(htlcs[0].htlc_id, i);
6636 SendEvent::from_event(events.remove(0))
6638 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6639 check_added_monitors!(nodes[1], 0);
6640 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6642 expect_pending_htlcs_forwardable!(nodes[1]);
6643 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6645 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6646 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6647 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6649 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6650 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6654 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6655 //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.
6656 let chanmon_cfgs = create_chanmon_cfgs(2);
6657 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6658 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6659 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6660 let channel_value = 100000;
6661 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6662 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6664 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6666 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6667 // Manually create a route over our max in flight (which our router normally automatically
6669 route.paths[0][0].fee_msat = max_in_flight + 1;
6670 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6671 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)));
6673 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6674 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);
6676 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6679 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6681 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6682 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6683 let chanmon_cfgs = create_chanmon_cfgs(2);
6684 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6685 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6686 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6687 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6688 let htlc_minimum_msat: u64;
6690 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6691 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6692 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6695 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6696 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6697 check_added_monitors!(nodes[0], 1);
6698 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6699 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6700 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6701 assert!(nodes[1].node.list_channels().is_empty());
6702 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6703 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()));
6704 check_added_monitors!(nodes[1], 1);
6705 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6709 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6710 //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
6711 let chanmon_cfgs = create_chanmon_cfgs(2);
6712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6714 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6715 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6717 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6718 let channel_reserve = chan_stat.channel_reserve_msat;
6719 let feerate = get_feerate!(nodes[0], chan.2);
6720 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6721 // The 2* and +1 are for the fee spike reserve.
6722 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6724 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6725 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6726 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6727 check_added_monitors!(nodes[0], 1);
6728 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6730 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6731 // at this time channel-initiatee receivers are not required to enforce that senders
6732 // respect the fee_spike_reserve.
6733 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6734 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6736 assert!(nodes[1].node.list_channels().is_empty());
6737 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6738 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6739 check_added_monitors!(nodes[1], 1);
6740 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6744 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6745 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6746 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6747 let chanmon_cfgs = create_chanmon_cfgs(2);
6748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6750 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6751 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6753 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6754 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6755 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6756 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6757 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6758 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6760 let mut msg = msgs::UpdateAddHTLC {
6764 payment_hash: our_payment_hash,
6765 cltv_expiry: htlc_cltv,
6766 onion_routing_packet: onion_packet.clone(),
6769 for i in 0..super::channel::OUR_MAX_HTLCS {
6770 msg.htlc_id = i as u64;
6771 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6773 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6774 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6776 assert!(nodes[1].node.list_channels().is_empty());
6777 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6778 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6779 check_added_monitors!(nodes[1], 1);
6780 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6784 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6785 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6786 let chanmon_cfgs = create_chanmon_cfgs(2);
6787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6789 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6790 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6792 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6793 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6794 check_added_monitors!(nodes[0], 1);
6795 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6796 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6797 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6799 assert!(nodes[1].node.list_channels().is_empty());
6800 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6801 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6802 check_added_monitors!(nodes[1], 1);
6803 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6807 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6808 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6809 let chanmon_cfgs = create_chanmon_cfgs(2);
6810 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6811 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6812 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6814 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6815 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6816 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6817 check_added_monitors!(nodes[0], 1);
6818 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6819 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6820 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6822 assert!(nodes[1].node.list_channels().is_empty());
6823 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6824 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6825 check_added_monitors!(nodes[1], 1);
6826 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6830 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6831 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6832 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6833 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6834 let chanmon_cfgs = create_chanmon_cfgs(2);
6835 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6836 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6837 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6839 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6840 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6841 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6842 check_added_monitors!(nodes[0], 1);
6843 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6844 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6846 //Disconnect and Reconnect
6847 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6848 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6849 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6850 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6851 assert_eq!(reestablish_1.len(), 1);
6852 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6853 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6854 assert_eq!(reestablish_2.len(), 1);
6855 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6856 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6857 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6858 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6861 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6862 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6863 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6864 check_added_monitors!(nodes[1], 1);
6865 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6867 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6869 assert!(nodes[1].node.list_channels().is_empty());
6870 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6871 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6872 check_added_monitors!(nodes[1], 1);
6873 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6877 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6878 //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.
6880 let chanmon_cfgs = create_chanmon_cfgs(2);
6881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6883 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6884 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6885 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6886 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6888 check_added_monitors!(nodes[0], 1);
6889 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6890 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6892 let update_msg = msgs::UpdateFulfillHTLC{
6895 payment_preimage: our_payment_preimage,
6898 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6900 assert!(nodes[0].node.list_channels().is_empty());
6901 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6902 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()));
6903 check_added_monitors!(nodes[0], 1);
6904 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6908 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6909 //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.
6911 let chanmon_cfgs = create_chanmon_cfgs(2);
6912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6914 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6915 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6917 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6918 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6919 check_added_monitors!(nodes[0], 1);
6920 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6921 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6923 let update_msg = msgs::UpdateFailHTLC{
6926 reason: msgs::OnionErrorPacket { data: Vec::new()},
6929 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6931 assert!(nodes[0].node.list_channels().is_empty());
6932 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6933 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()));
6934 check_added_monitors!(nodes[0], 1);
6935 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6939 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6940 //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.
6942 let chanmon_cfgs = create_chanmon_cfgs(2);
6943 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6944 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6945 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6946 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6948 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6949 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6950 check_added_monitors!(nodes[0], 1);
6951 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6952 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6953 let update_msg = msgs::UpdateFailMalformedHTLC{
6956 sha256_of_onion: [1; 32],
6957 failure_code: 0x8000,
6960 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6962 assert!(nodes[0].node.list_channels().is_empty());
6963 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6964 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()));
6965 check_added_monitors!(nodes[0], 1);
6966 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6970 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6971 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6973 let chanmon_cfgs = create_chanmon_cfgs(2);
6974 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6975 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6976 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6977 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6979 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6981 nodes[1].node.claim_funds(our_payment_preimage);
6982 check_added_monitors!(nodes[1], 1);
6983 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6985 let events = nodes[1].node.get_and_clear_pending_msg_events();
6986 assert_eq!(events.len(), 1);
6987 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6989 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, .. } } => {
6990 assert!(update_add_htlcs.is_empty());
6991 assert_eq!(update_fulfill_htlcs.len(), 1);
6992 assert!(update_fail_htlcs.is_empty());
6993 assert!(update_fail_malformed_htlcs.is_empty());
6994 assert!(update_fee.is_none());
6995 update_fulfill_htlcs[0].clone()
6997 _ => panic!("Unexpected event"),
7001 update_fulfill_msg.htlc_id = 1;
7003 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7005 assert!(nodes[0].node.list_channels().is_empty());
7006 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7007 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7008 check_added_monitors!(nodes[0], 1);
7009 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7013 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7014 //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.
7016 let chanmon_cfgs = create_chanmon_cfgs(2);
7017 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7018 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7019 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7020 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7022 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7024 nodes[1].node.claim_funds(our_payment_preimage);
7025 check_added_monitors!(nodes[1], 1);
7026 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7028 let events = nodes[1].node.get_and_clear_pending_msg_events();
7029 assert_eq!(events.len(), 1);
7030 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7032 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, .. } } => {
7033 assert!(update_add_htlcs.is_empty());
7034 assert_eq!(update_fulfill_htlcs.len(), 1);
7035 assert!(update_fail_htlcs.is_empty());
7036 assert!(update_fail_malformed_htlcs.is_empty());
7037 assert!(update_fee.is_none());
7038 update_fulfill_htlcs[0].clone()
7040 _ => panic!("Unexpected event"),
7044 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7046 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7048 assert!(nodes[0].node.list_channels().is_empty());
7049 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7050 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7051 check_added_monitors!(nodes[0], 1);
7052 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7056 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7057 //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.
7059 let chanmon_cfgs = create_chanmon_cfgs(2);
7060 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7061 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7062 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7063 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7065 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7066 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7067 check_added_monitors!(nodes[0], 1);
7069 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7070 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7072 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7073 check_added_monitors!(nodes[1], 0);
7074 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7076 let events = nodes[1].node.get_and_clear_pending_msg_events();
7078 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7080 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, .. } } => {
7081 assert!(update_add_htlcs.is_empty());
7082 assert!(update_fulfill_htlcs.is_empty());
7083 assert!(update_fail_htlcs.is_empty());
7084 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7085 assert!(update_fee.is_none());
7086 update_fail_malformed_htlcs[0].clone()
7088 _ => panic!("Unexpected event"),
7091 update_msg.failure_code &= !0x8000;
7092 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7094 assert!(nodes[0].node.list_channels().is_empty());
7095 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7096 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7097 check_added_monitors!(nodes[0], 1);
7098 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7102 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7103 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7104 // * 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.
7106 let chanmon_cfgs = create_chanmon_cfgs(3);
7107 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7108 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7109 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7110 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7111 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7113 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7116 let mut payment_event = {
7117 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7118 check_added_monitors!(nodes[0], 1);
7119 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7120 assert_eq!(events.len(), 1);
7121 SendEvent::from_event(events.remove(0))
7123 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7124 check_added_monitors!(nodes[1], 0);
7125 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7126 expect_pending_htlcs_forwardable!(nodes[1]);
7127 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7128 assert_eq!(events_2.len(), 1);
7129 check_added_monitors!(nodes[1], 1);
7130 payment_event = SendEvent::from_event(events_2.remove(0));
7131 assert_eq!(payment_event.msgs.len(), 1);
7134 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7135 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7136 check_added_monitors!(nodes[2], 0);
7137 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7139 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7140 assert_eq!(events_3.len(), 1);
7141 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7143 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 } } => {
7144 assert!(update_add_htlcs.is_empty());
7145 assert!(update_fulfill_htlcs.is_empty());
7146 assert!(update_fail_htlcs.is_empty());
7147 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7148 assert!(update_fee.is_none());
7149 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7151 _ => panic!("Unexpected event"),
7155 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7157 check_added_monitors!(nodes[1], 0);
7158 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7159 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 }]);
7160 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7161 assert_eq!(events_4.len(), 1);
7163 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7165 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, .. } } => {
7166 assert!(update_add_htlcs.is_empty());
7167 assert!(update_fulfill_htlcs.is_empty());
7168 assert_eq!(update_fail_htlcs.len(), 1);
7169 assert!(update_fail_malformed_htlcs.is_empty());
7170 assert!(update_fee.is_none());
7172 _ => panic!("Unexpected event"),
7175 check_added_monitors!(nodes[1], 1);
7179 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
7180 let chanmon_cfgs = create_chanmon_cfgs(3);
7181 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7182 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7183 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7184 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7185 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7187 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
7190 let mut payment_event = {
7191 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7192 check_added_monitors!(nodes[0], 1);
7193 SendEvent::from_node(&nodes[0])
7196 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7197 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7198 expect_pending_htlcs_forwardable!(nodes[1]);
7199 check_added_monitors!(nodes[1], 1);
7200 payment_event = SendEvent::from_node(&nodes[1]);
7201 assert_eq!(payment_event.msgs.len(), 1);
7204 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
7205 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7206 check_added_monitors!(nodes[2], 0);
7207 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7209 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7210 assert_eq!(events_3.len(), 1);
7212 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7213 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7214 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7215 update_msg.failure_code |= 0x2000;
7217 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7218 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7220 _ => panic!("Unexpected event"),
7223 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7224 vec![HTLCDestination::NextHopChannel {
7225 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7226 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7227 assert_eq!(events_4.len(), 1);
7228 check_added_monitors!(nodes[1], 1);
7231 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7232 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7233 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7235 _ => panic!("Unexpected event"),
7238 let events_5 = nodes[0].node.get_and_clear_pending_events();
7239 assert_eq!(events_5.len(), 1);
7241 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7242 // the node originating the error to its next hop.
7244 Event::PaymentPathFailed { network_update:
7245 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
7247 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7248 assert!(is_permanent);
7249 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7251 _ => panic!("Unexpected event"),
7254 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7257 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7258 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7259 // 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
7260 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7262 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7263 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7264 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7265 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7266 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7267 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7269 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7271 // We route 2 dust-HTLCs between A and B
7272 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7273 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7274 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7276 // Cache one local commitment tx as previous
7277 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7279 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7280 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7281 check_added_monitors!(nodes[1], 0);
7282 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7283 check_added_monitors!(nodes[1], 1);
7285 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7286 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7287 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7288 check_added_monitors!(nodes[0], 1);
7290 // Cache one local commitment tx as lastest
7291 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7293 let events = nodes[0].node.get_and_clear_pending_msg_events();
7295 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7296 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7298 _ => panic!("Unexpected event"),
7301 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7302 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7304 _ => panic!("Unexpected event"),
7307 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7308 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7309 if announce_latest {
7310 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7312 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7315 check_closed_broadcast!(nodes[0], true);
7316 check_added_monitors!(nodes[0], 1);
7317 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7319 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7320 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7321 let events = nodes[0].node.get_and_clear_pending_events();
7322 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7323 assert_eq!(events.len(), 2);
7324 let mut first_failed = false;
7325 for event in events {
7327 Event::PaymentPathFailed { payment_hash, .. } => {
7328 if payment_hash == payment_hash_1 {
7329 assert!(!first_failed);
7330 first_failed = true;
7332 assert_eq!(payment_hash, payment_hash_2);
7335 _ => panic!("Unexpected event"),
7341 fn test_failure_delay_dust_htlc_local_commitment() {
7342 do_test_failure_delay_dust_htlc_local_commitment(true);
7343 do_test_failure_delay_dust_htlc_local_commitment(false);
7346 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7347 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7348 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7349 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7350 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7351 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7352 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7354 let chanmon_cfgs = create_chanmon_cfgs(3);
7355 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7356 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7357 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7358 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7360 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7362 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7363 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7365 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7366 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7368 // We revoked bs_commitment_tx
7370 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7371 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7374 let mut timeout_tx = Vec::new();
7376 // We fail dust-HTLC 1 by broadcast of local commitment tx
7377 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7378 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7379 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7380 expect_payment_failed!(nodes[0], dust_hash, false);
7382 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7383 check_closed_broadcast!(nodes[0], true);
7384 check_added_monitors!(nodes[0], 1);
7385 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7386 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7387 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7388 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7389 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7390 mine_transaction(&nodes[0], &timeout_tx[0]);
7391 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7392 expect_payment_failed!(nodes[0], non_dust_hash, false);
7394 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7395 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7396 check_closed_broadcast!(nodes[0], true);
7397 check_added_monitors!(nodes[0], 1);
7398 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7399 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7401 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7402 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7403 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7404 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7405 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7406 // dust HTLC should have been failed.
7407 expect_payment_failed!(nodes[0], dust_hash, false);
7410 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7412 assert_eq!(timeout_tx[0].lock_time.0, 0);
7414 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7415 mine_transaction(&nodes[0], &timeout_tx[0]);
7416 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7417 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7418 expect_payment_failed!(nodes[0], non_dust_hash, false);
7423 fn test_sweep_outbound_htlc_failure_update() {
7424 do_test_sweep_outbound_htlc_failure_update(false, true);
7425 do_test_sweep_outbound_htlc_failure_update(false, false);
7426 do_test_sweep_outbound_htlc_failure_update(true, false);
7430 fn test_user_configurable_csv_delay() {
7431 // We test our channel constructors yield errors when we pass them absurd csv delay
7433 let mut low_our_to_self_config = UserConfig::default();
7434 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7435 let mut high_their_to_self_config = UserConfig::default();
7436 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7437 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7438 let chanmon_cfgs = create_chanmon_cfgs(2);
7439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7441 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7443 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7444 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7445 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
7446 &low_our_to_self_config, 0, 42)
7449 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())); },
7450 _ => panic!("Unexpected event"),
7452 } else { assert!(false) }
7454 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7455 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7456 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7457 open_channel.to_self_delay = 200;
7458 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7459 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7460 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7463 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())); },
7464 _ => panic!("Unexpected event"),
7466 } else { assert!(false); }
7468 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7469 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7470 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7471 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7472 accept_channel.to_self_delay = 200;
7473 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
7475 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7477 &ErrorAction::SendErrorMessage { ref msg } => {
7478 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()));
7479 reason_msg = msg.data.clone();
7483 } else { panic!(); }
7484 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7486 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7487 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7488 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7489 open_channel.to_self_delay = 200;
7490 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7491 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7492 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7495 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())); },
7496 _ => panic!("Unexpected event"),
7498 } else { assert!(false); }
7501 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7502 // When we get a data_loss_protect proving we're behind, we immediately panic as the
7503 // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7504 // panic message informs the user they should force-close without broadcasting, which is tested
7505 // if `reconnect_panicing` is not set.
7511 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7512 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7513 // during signing due to revoked tx
7514 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7515 let keys_manager = &chanmon_cfgs[0].keys_manager;
7518 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7519 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7520 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7522 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7524 // Cache node A state before any channel update
7525 let previous_node_state = nodes[0].node.encode();
7526 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7527 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7529 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7530 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7532 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7533 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7535 // Restore node A from previous state
7536 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7537 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7538 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7539 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7540 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7541 persister = test_utils::TestPersister::new();
7542 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7544 let mut channel_monitors = HashMap::new();
7545 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7546 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7547 keys_manager: keys_manager,
7548 fee_estimator: &fee_estimator,
7549 chain_monitor: &monitor,
7551 tx_broadcaster: &tx_broadcaster,
7552 default_config: UserConfig::default(),
7556 nodes[0].node = &node_state_0;
7557 assert_eq!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor),
7558 ChannelMonitorUpdateStatus::Completed);
7559 nodes[0].chain_monitor = &monitor;
7560 nodes[0].chain_source = &chain_source;
7562 check_added_monitors!(nodes[0], 1);
7564 if reconnect_panicing {
7565 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7566 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7568 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7570 // Check we close channel detecting A is fallen-behind
7571 // Check that we sent the warning message when we detected that A has fallen behind,
7572 // and give the possibility for A to recover from the warning.
7573 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7574 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7575 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7578 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7579 // The node B should not broadcast the transaction to force close the channel!
7580 assert!(node_txn.is_empty());
7583 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7584 // Check A panics upon seeing proof it has fallen behind.
7585 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7586 return; // By this point we should have panic'ed!
7589 nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7590 check_added_monitors!(nodes[0], 1);
7591 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7593 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7594 assert_eq!(node_txn.len(), 0);
7597 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7598 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7599 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7601 &ErrorAction::SendErrorMessage { ref msg } => {
7602 assert_eq!(msg.data, "Channel force-closed");
7604 _ => panic!("Unexpected event!"),
7607 panic!("Unexpected event {:?}", msg)
7611 // after the warning message sent by B, we should not able to
7612 // use the channel, or reconnect with success to the channel.
7613 assert!(nodes[0].node.list_usable_channels().is_empty());
7614 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7615 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7616 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7618 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7619 let mut err_msgs_0 = Vec::with_capacity(1);
7620 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7621 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7623 &ErrorAction::SendErrorMessage { ref msg } => {
7624 assert_eq!(msg.data, "Failed to find corresponding channel");
7625 err_msgs_0.push(msg.clone());
7627 _ => panic!("Unexpected event!"),
7630 panic!("Unexpected event!");
7633 assert_eq!(err_msgs_0.len(), 1);
7634 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7635 assert!(nodes[1].node.list_usable_channels().is_empty());
7636 check_added_monitors!(nodes[1], 1);
7637 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7638 check_closed_broadcast!(nodes[1], false);
7643 fn test_data_loss_protect_showing_stale_state_panics() {
7644 do_test_data_loss_protect(true);
7648 fn test_force_close_without_broadcast() {
7649 do_test_data_loss_protect(false);
7653 fn test_check_htlc_underpaying() {
7654 // Send payment through A -> B but A is maliciously
7655 // sending a probe payment (i.e less than expected value0
7656 // to B, B should refuse payment.
7658 let chanmon_cfgs = create_chanmon_cfgs(2);
7659 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7660 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7661 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7663 // Create some initial channels
7664 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7666 let scorer = test_utils::TestScorer::with_penalty(0);
7667 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7668 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7669 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();
7670 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7671 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7672 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7673 check_added_monitors!(nodes[0], 1);
7675 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7676 assert_eq!(events.len(), 1);
7677 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7678 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7679 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7681 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7682 // and then will wait a second random delay before failing the HTLC back:
7683 expect_pending_htlcs_forwardable!(nodes[1]);
7684 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7686 // Node 3 is expecting payment of 100_000 but received 10_000,
7687 // it should fail htlc like we didn't know the preimage.
7688 nodes[1].node.process_pending_htlc_forwards();
7690 let events = nodes[1].node.get_and_clear_pending_msg_events();
7691 assert_eq!(events.len(), 1);
7692 let (update_fail_htlc, commitment_signed) = match events[0] {
7693 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 } } => {
7694 assert!(update_add_htlcs.is_empty());
7695 assert!(update_fulfill_htlcs.is_empty());
7696 assert_eq!(update_fail_htlcs.len(), 1);
7697 assert!(update_fail_malformed_htlcs.is_empty());
7698 assert!(update_fee.is_none());
7699 (update_fail_htlcs[0].clone(), commitment_signed)
7701 _ => panic!("Unexpected event"),
7703 check_added_monitors!(nodes[1], 1);
7705 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7706 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7708 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7709 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7710 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7711 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7715 fn test_announce_disable_channels() {
7716 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7717 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7719 let chanmon_cfgs = create_chanmon_cfgs(2);
7720 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7721 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7722 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7724 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7725 create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7726 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7729 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7730 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7732 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7733 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7734 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7735 assert_eq!(msg_events.len(), 3);
7736 let mut chans_disabled = HashMap::new();
7737 for e in msg_events {
7739 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7740 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7741 // Check that each channel gets updated exactly once
7742 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7743 panic!("Generated ChannelUpdate for wrong chan!");
7746 _ => panic!("Unexpected event"),
7750 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7751 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7752 assert_eq!(reestablish_1.len(), 3);
7753 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7754 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7755 assert_eq!(reestablish_2.len(), 3);
7757 // Reestablish chan_1
7758 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7759 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7760 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7761 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7762 // Reestablish chan_2
7763 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7764 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7765 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7766 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7767 // Reestablish chan_3
7768 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7769 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7770 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7771 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7773 nodes[0].node.timer_tick_occurred();
7774 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7775 nodes[0].node.timer_tick_occurred();
7776 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7777 assert_eq!(msg_events.len(), 3);
7778 for e in msg_events {
7780 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7781 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7782 match chans_disabled.remove(&msg.contents.short_channel_id) {
7783 // Each update should have a higher timestamp than the previous one, replacing
7785 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7786 None => panic!("Generated ChannelUpdate for wrong chan!"),
7789 _ => panic!("Unexpected event"),
7792 // Check that each channel gets updated exactly once
7793 assert!(chans_disabled.is_empty());
7797 fn test_bump_penalty_txn_on_revoked_commitment() {
7798 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7799 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7801 let chanmon_cfgs = create_chanmon_cfgs(2);
7802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7804 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7806 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7808 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7809 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7810 .with_features(channelmanager::provided_invoice_features());
7811 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7812 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7814 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7815 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7816 assert_eq!(revoked_txn[0].output.len(), 4);
7817 assert_eq!(revoked_txn[0].input.len(), 1);
7818 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7819 let revoked_txid = revoked_txn[0].txid();
7821 let mut penalty_sum = 0;
7822 for outp in revoked_txn[0].output.iter() {
7823 if outp.script_pubkey.is_v0_p2wsh() {
7824 penalty_sum += outp.value;
7828 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7829 let header_114 = connect_blocks(&nodes[1], 14);
7831 // Actually revoke tx by claiming a HTLC
7832 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7833 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7834 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7835 check_added_monitors!(nodes[1], 1);
7837 // One or more justice tx should have been broadcast, check it
7841 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7842 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7843 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7844 assert_eq!(node_txn[0].output.len(), 1);
7845 check_spends!(node_txn[0], revoked_txn[0]);
7846 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7847 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7848 penalty_1 = node_txn[0].txid();
7852 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7853 connect_blocks(&nodes[1], 15);
7854 let mut penalty_2 = penalty_1;
7855 let mut feerate_2 = 0;
7857 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7858 assert_eq!(node_txn.len(), 1);
7859 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7860 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7861 assert_eq!(node_txn[0].output.len(), 1);
7862 check_spends!(node_txn[0], revoked_txn[0]);
7863 penalty_2 = node_txn[0].txid();
7864 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7865 assert_ne!(penalty_2, penalty_1);
7866 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7867 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7868 // Verify 25% bump heuristic
7869 assert!(feerate_2 * 100 >= feerate_1 * 125);
7873 assert_ne!(feerate_2, 0);
7875 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7876 connect_blocks(&nodes[1], 1);
7878 let mut feerate_3 = 0;
7880 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7881 assert_eq!(node_txn.len(), 1);
7882 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7883 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7884 assert_eq!(node_txn[0].output.len(), 1);
7885 check_spends!(node_txn[0], revoked_txn[0]);
7886 penalty_3 = node_txn[0].txid();
7887 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7888 assert_ne!(penalty_3, penalty_2);
7889 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7890 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7891 // Verify 25% bump heuristic
7892 assert!(feerate_3 * 100 >= feerate_2 * 125);
7896 assert_ne!(feerate_3, 0);
7898 nodes[1].node.get_and_clear_pending_events();
7899 nodes[1].node.get_and_clear_pending_msg_events();
7903 fn test_bump_penalty_txn_on_revoked_htlcs() {
7904 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7905 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7907 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7908 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7911 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7913 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7914 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7915 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7916 let scorer = test_utils::TestScorer::with_penalty(0);
7917 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7918 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7919 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7920 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7921 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7922 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7923 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7924 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7926 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7927 assert_eq!(revoked_local_txn[0].input.len(), 1);
7928 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7930 // Revoke local commitment tx
7931 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7933 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7934 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7935 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7936 check_closed_broadcast!(nodes[1], true);
7937 check_added_monitors!(nodes[1], 1);
7938 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7939 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7941 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7942 assert_eq!(revoked_htlc_txn.len(), 3);
7943 check_spends!(revoked_htlc_txn[1], chan.3);
7945 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7946 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7947 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7949 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7950 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7951 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7952 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7954 // Broadcast set of revoked txn on A
7955 let hash_128 = connect_blocks(&nodes[0], 40);
7956 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7957 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7958 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7959 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7960 let events = nodes[0].node.get_and_clear_pending_events();
7961 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7962 match events.last().unwrap() {
7963 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7964 _ => panic!("Unexpected event"),
7970 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7971 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7972 // Verify claim tx are spending revoked HTLC txn
7974 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7975 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7976 // which are included in the same block (they are broadcasted because we scan the
7977 // transactions linearly and generate claims as we go, they likely should be removed in the
7979 assert_eq!(node_txn[0].input.len(), 1);
7980 check_spends!(node_txn[0], revoked_local_txn[0]);
7981 assert_eq!(node_txn[1].input.len(), 1);
7982 check_spends!(node_txn[1], revoked_local_txn[0]);
7983 assert_eq!(node_txn[2].input.len(), 1);
7984 check_spends!(node_txn[2], revoked_local_txn[0]);
7986 // Each of the three justice transactions claim a separate (single) output of the three
7987 // available, which we check here:
7988 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7989 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7990 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7992 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7993 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7995 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7996 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7997 // a remote commitment tx has already been confirmed).
7998 check_spends!(node_txn[3], chan.3);
8000 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
8001 // output, checked above).
8002 assert_eq!(node_txn[4].input.len(), 2);
8003 assert_eq!(node_txn[4].output.len(), 1);
8004 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8006 first = node_txn[4].txid();
8007 // Store both feerates for later comparison
8008 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
8009 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
8010 penalty_txn = vec![node_txn[2].clone()];
8014 // Connect one more block to see if bumped penalty are issued for HTLC txn
8015 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8016 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8017 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8018 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
8020 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8021 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
8023 check_spends!(node_txn[0], revoked_local_txn[0]);
8024 check_spends!(node_txn[1], revoked_local_txn[0]);
8025 // Note that these are both bogus - they spend outputs already claimed in block 129:
8026 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
8027 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8029 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8030 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
8036 // Few more blocks to confirm penalty txn
8037 connect_blocks(&nodes[0], 4);
8038 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8039 let header_144 = connect_blocks(&nodes[0], 9);
8041 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8042 assert_eq!(node_txn.len(), 1);
8044 assert_eq!(node_txn[0].input.len(), 2);
8045 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8046 // Verify bumped tx is different and 25% bump heuristic
8047 assert_ne!(first, node_txn[0].txid());
8048 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
8049 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
8050 assert!(feerate_2 * 100 > feerate_1 * 125);
8051 let txn = vec![node_txn[0].clone()];
8055 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8056 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8057 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8058 connect_blocks(&nodes[0], 20);
8060 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8061 // We verify than no new transaction has been broadcast because previously
8062 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8063 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8064 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8065 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8066 // up bumped justice generation.
8067 assert_eq!(node_txn.len(), 0);
8070 check_closed_broadcast!(nodes[0], true);
8071 check_added_monitors!(nodes[0], 1);
8075 fn test_bump_penalty_txn_on_remote_commitment() {
8076 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8077 // we're able to claim outputs on remote commitment transaction before timelocks expiration
8080 // Provide preimage for one
8081 // Check aggregation
8083 let chanmon_cfgs = create_chanmon_cfgs(2);
8084 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8085 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8086 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8088 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8089 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8090 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8092 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8093 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8094 assert_eq!(remote_txn[0].output.len(), 4);
8095 assert_eq!(remote_txn[0].input.len(), 1);
8096 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8098 // Claim a HTLC without revocation (provide B monitor with preimage)
8099 nodes[1].node.claim_funds(payment_preimage);
8100 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8101 mine_transaction(&nodes[1], &remote_txn[0]);
8102 check_added_monitors!(nodes[1], 2);
8103 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8105 // One or more claim tx should have been broadcast, check it
8109 let feerate_timeout;
8110 let feerate_preimage;
8112 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8113 // 5 transactions including:
8114 // local commitment + HTLC-Success
8115 // preimage and timeout sweeps from remote commitment + preimage sweep bump
8116 assert_eq!(node_txn.len(), 5);
8117 assert_eq!(node_txn[0].input.len(), 1);
8118 assert_eq!(node_txn[3].input.len(), 1);
8119 assert_eq!(node_txn[4].input.len(), 1);
8120 check_spends!(node_txn[0], remote_txn[0]);
8121 check_spends!(node_txn[3], remote_txn[0]);
8122 check_spends!(node_txn[4], remote_txn[0]);
8124 check_spends!(node_txn[1], chan.3); // local commitment
8125 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
8127 preimage = node_txn[0].txid();
8128 let index = node_txn[0].input[0].previous_output.vout;
8129 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8130 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8132 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
8133 (node_txn[3].clone(), node_txn[4].clone())
8135 (node_txn[4].clone(), node_txn[3].clone())
8138 preimage_bump = preimage_bump_tx;
8139 check_spends!(preimage_bump, remote_txn[0]);
8140 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
8142 timeout = timeout_tx.txid();
8143 let index = timeout_tx.input[0].previous_output.vout;
8144 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
8145 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
8149 assert_ne!(feerate_timeout, 0);
8150 assert_ne!(feerate_preimage, 0);
8152 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8153 connect_blocks(&nodes[1], 15);
8155 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8156 assert_eq!(node_txn.len(), 1);
8157 assert_eq!(node_txn[0].input.len(), 1);
8158 assert_eq!(preimage_bump.input.len(), 1);
8159 check_spends!(node_txn[0], remote_txn[0]);
8160 check_spends!(preimage_bump, remote_txn[0]);
8162 let index = preimage_bump.input[0].previous_output.vout;
8163 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8164 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8165 assert!(new_feerate * 100 > feerate_timeout * 125);
8166 assert_ne!(timeout, preimage_bump.txid());
8168 let index = node_txn[0].input[0].previous_output.vout;
8169 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8170 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8171 assert!(new_feerate * 100 > feerate_preimage * 125);
8172 assert_ne!(preimage, node_txn[0].txid());
8177 nodes[1].node.get_and_clear_pending_events();
8178 nodes[1].node.get_and_clear_pending_msg_events();
8182 fn test_counterparty_raa_skip_no_crash() {
8183 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8184 // commitment transaction, we would have happily carried on and provided them the next
8185 // commitment transaction based on one RAA forward. This would probably eventually have led to
8186 // channel closure, but it would not have resulted in funds loss. Still, our
8187 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8188 // check simply that the channel is closed in response to such an RAA, but don't check whether
8189 // we decide to punish our counterparty for revoking their funds (as we don't currently
8191 let chanmon_cfgs = create_chanmon_cfgs(2);
8192 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8194 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8195 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
8197 let per_commitment_secret;
8198 let next_per_commitment_point;
8200 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8201 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8203 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8205 // Make signer believe we got a counterparty signature, so that it allows the revocation
8206 keys.get_enforcement_state().last_holder_commitment -= 1;
8207 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8209 // Must revoke without gaps
8210 keys.get_enforcement_state().last_holder_commitment -= 1;
8211 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8213 keys.get_enforcement_state().last_holder_commitment -= 1;
8214 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8215 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8218 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8219 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8220 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8221 check_added_monitors!(nodes[1], 1);
8222 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8226 fn test_bump_txn_sanitize_tracking_maps() {
8227 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8228 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8230 let chanmon_cfgs = create_chanmon_cfgs(2);
8231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8233 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8235 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8236 // Lock HTLC in both directions
8237 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8238 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8240 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8241 assert_eq!(revoked_local_txn[0].input.len(), 1);
8242 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8244 // Revoke local commitment tx
8245 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8247 // Broadcast set of revoked txn on A
8248 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8249 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8250 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8252 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8253 check_closed_broadcast!(nodes[0], true);
8254 check_added_monitors!(nodes[0], 1);
8255 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8257 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8258 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8259 check_spends!(node_txn[0], revoked_local_txn[0]);
8260 check_spends!(node_txn[1], revoked_local_txn[0]);
8261 check_spends!(node_txn[2], revoked_local_txn[0]);
8262 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8266 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8267 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8268 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8270 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8271 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8272 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8277 fn test_pending_claimed_htlc_no_balance_underflow() {
8278 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8279 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8280 let chanmon_cfgs = create_chanmon_cfgs(2);
8281 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8282 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8283 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8284 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8286 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8287 nodes[1].node.claim_funds(payment_preimage);
8288 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8289 check_added_monitors!(nodes[1], 1);
8290 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8292 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8293 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8294 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8295 check_added_monitors!(nodes[0], 1);
8296 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8298 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8299 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8300 // can get our balance.
8302 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8303 // the public key of the only hop. This works around ChannelDetails not showing the
8304 // almost-claimed HTLC as available balance.
8305 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8306 route.payment_params = None; // This is all wrong, but unnecessary
8307 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8308 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8309 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8311 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8315 fn test_channel_conf_timeout() {
8316 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8317 // confirm within 2016 blocks, as recommended by BOLT 2.
8318 let chanmon_cfgs = create_chanmon_cfgs(2);
8319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8321 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8323 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8325 // The outbound node should wait forever for confirmation:
8326 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8327 // copied here instead of directly referencing the constant.
8328 connect_blocks(&nodes[0], 2016);
8329 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8331 // The inbound node should fail the channel after exactly 2016 blocks
8332 connect_blocks(&nodes[1], 2015);
8333 check_added_monitors!(nodes[1], 0);
8334 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8336 connect_blocks(&nodes[1], 1);
8337 check_added_monitors!(nodes[1], 1);
8338 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8339 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8340 assert_eq!(close_ev.len(), 1);
8342 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8343 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8344 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8346 _ => panic!("Unexpected event"),
8351 fn test_override_channel_config() {
8352 let chanmon_cfgs = create_chanmon_cfgs(2);
8353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8357 // Node0 initiates a channel to node1 using the override config.
8358 let mut override_config = UserConfig::default();
8359 override_config.channel_handshake_config.our_to_self_delay = 200;
8361 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8363 // Assert the channel created by node0 is using the override config.
8364 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8365 assert_eq!(res.channel_flags, 0);
8366 assert_eq!(res.to_self_delay, 200);
8370 fn test_override_0msat_htlc_minimum() {
8371 let mut zero_config = UserConfig::default();
8372 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8373 let chanmon_cfgs = create_chanmon_cfgs(2);
8374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8376 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8378 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8379 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8380 assert_eq!(res.htlc_minimum_msat, 1);
8382 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8383 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8384 assert_eq!(res.htlc_minimum_msat, 1);
8388 fn test_channel_update_has_correct_htlc_maximum_msat() {
8389 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8390 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8391 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8392 // 90% of the `channel_value`.
8393 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8395 let mut config_30_percent = UserConfig::default();
8396 config_30_percent.channel_handshake_config.announced_channel = true;
8397 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8398 let mut config_50_percent = UserConfig::default();
8399 config_50_percent.channel_handshake_config.announced_channel = true;
8400 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8401 let mut config_95_percent = UserConfig::default();
8402 config_95_percent.channel_handshake_config.announced_channel = true;
8403 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8404 let mut config_100_percent = UserConfig::default();
8405 config_100_percent.channel_handshake_config.announced_channel = true;
8406 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8408 let chanmon_cfgs = create_chanmon_cfgs(4);
8409 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8410 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)]);
8411 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8413 let channel_value_satoshis = 100000;
8414 let channel_value_msat = channel_value_satoshis * 1000;
8415 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8416 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8417 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8419 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8420 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8422 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8423 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8424 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8425 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8426 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8427 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8429 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8430 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8432 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8433 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8434 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8436 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8440 fn test_manually_accept_inbound_channel_request() {
8441 let mut manually_accept_conf = UserConfig::default();
8442 manually_accept_conf.manually_accept_inbound_channels = true;
8443 let chanmon_cfgs = create_chanmon_cfgs(2);
8444 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8445 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8446 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8448 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8449 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8451 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8453 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8454 // accepting the inbound channel request.
8455 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8457 let events = nodes[1].node.get_and_clear_pending_events();
8459 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8460 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8462 _ => panic!("Unexpected event"),
8465 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8466 assert_eq!(accept_msg_ev.len(), 1);
8468 match accept_msg_ev[0] {
8469 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8470 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8472 _ => panic!("Unexpected event"),
8475 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8477 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8478 assert_eq!(close_msg_ev.len(), 1);
8480 let events = nodes[1].node.get_and_clear_pending_events();
8482 Event::ChannelClosed { user_channel_id, .. } => {
8483 assert_eq!(user_channel_id, 23);
8485 _ => panic!("Unexpected event"),
8490 fn test_manually_reject_inbound_channel_request() {
8491 let mut manually_accept_conf = UserConfig::default();
8492 manually_accept_conf.manually_accept_inbound_channels = true;
8493 let chanmon_cfgs = create_chanmon_cfgs(2);
8494 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8495 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8496 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8498 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8499 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8501 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8503 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8504 // rejecting the inbound channel request.
8505 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8507 let events = nodes[1].node.get_and_clear_pending_events();
8509 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8510 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8512 _ => panic!("Unexpected event"),
8515 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8516 assert_eq!(close_msg_ev.len(), 1);
8518 match close_msg_ev[0] {
8519 MessageSendEvent::HandleError { ref node_id, .. } => {
8520 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8522 _ => panic!("Unexpected event"),
8524 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8528 fn test_reject_funding_before_inbound_channel_accepted() {
8529 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8530 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8531 // the node operator before the counterparty sends a `FundingCreated` message. If a
8532 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8533 // and the channel should be closed.
8534 let mut manually_accept_conf = UserConfig::default();
8535 manually_accept_conf.manually_accept_inbound_channels = true;
8536 let chanmon_cfgs = create_chanmon_cfgs(2);
8537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8539 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8541 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8542 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8543 let temp_channel_id = res.temporary_channel_id;
8545 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8547 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8548 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8550 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8551 nodes[1].node.get_and_clear_pending_events();
8553 // Get the `AcceptChannel` message of `nodes[1]` without calling
8554 // `ChannelManager::accept_inbound_channel`, which generates a
8555 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8556 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8557 // succeed when `nodes[0]` is passed to it.
8558 let accept_chan_msg = {
8560 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8561 channel.get_accept_channel_message()
8563 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8565 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8567 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8568 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8570 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8571 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8573 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8574 assert_eq!(close_msg_ev.len(), 1);
8576 let expected_err = "FundingCreated message received before the channel was accepted";
8577 match close_msg_ev[0] {
8578 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8579 assert_eq!(msg.channel_id, temp_channel_id);
8580 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8581 assert_eq!(msg.data, expected_err);
8583 _ => panic!("Unexpected event"),
8586 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8590 fn test_can_not_accept_inbound_channel_twice() {
8591 let mut manually_accept_conf = UserConfig::default();
8592 manually_accept_conf.manually_accept_inbound_channels = true;
8593 let chanmon_cfgs = create_chanmon_cfgs(2);
8594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8598 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8599 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8601 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8603 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8604 // accepting the inbound channel request.
8605 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8607 let events = nodes[1].node.get_and_clear_pending_events();
8609 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8610 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8611 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8613 Err(APIError::APIMisuseError { err }) => {
8614 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8616 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8617 Err(_) => panic!("Unexpected Error"),
8620 _ => panic!("Unexpected event"),
8623 // Ensure that the channel wasn't closed after attempting to accept it twice.
8624 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8625 assert_eq!(accept_msg_ev.len(), 1);
8627 match accept_msg_ev[0] {
8628 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8629 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8631 _ => panic!("Unexpected event"),
8636 fn test_can_not_accept_unknown_inbound_channel() {
8637 let chanmon_cfg = create_chanmon_cfgs(2);
8638 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8639 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8640 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8642 let unknown_channel_id = [0; 32];
8643 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8645 Err(APIError::ChannelUnavailable { err }) => {
8646 assert_eq!(err, "Can't accept a channel that doesn't exist");
8648 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8649 Err(_) => panic!("Unexpected Error"),
8654 fn test_simple_mpp() {
8655 // Simple test of sending a multi-path payment.
8656 let chanmon_cfgs = create_chanmon_cfgs(4);
8657 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8658 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8659 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8661 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8662 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8663 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8664 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8666 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8667 let path = route.paths[0].clone();
8668 route.paths.push(path);
8669 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8670 route.paths[0][0].short_channel_id = chan_1_id;
8671 route.paths[0][1].short_channel_id = chan_3_id;
8672 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8673 route.paths[1][0].short_channel_id = chan_2_id;
8674 route.paths[1][1].short_channel_id = chan_4_id;
8675 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8676 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8680 fn test_preimage_storage() {
8681 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8682 let chanmon_cfgs = create_chanmon_cfgs(2);
8683 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8684 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8685 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8687 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8690 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8691 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8692 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8693 check_added_monitors!(nodes[0], 1);
8694 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8695 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8696 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8697 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8699 // Note that after leaving the above scope we have no knowledge of any arguments or return
8700 // values from previous calls.
8701 expect_pending_htlcs_forwardable!(nodes[1]);
8702 let events = nodes[1].node.get_and_clear_pending_events();
8703 assert_eq!(events.len(), 1);
8705 Event::PaymentReceived { ref purpose, .. } => {
8707 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8708 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8710 _ => panic!("expected PaymentPurpose::InvoicePayment")
8713 _ => panic!("Unexpected event"),
8718 #[allow(deprecated)]
8719 fn test_secret_timeout() {
8720 // Simple test of payment secret storage time outs. After
8721 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8722 let chanmon_cfgs = create_chanmon_cfgs(2);
8723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8727 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8729 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8731 // We should fail to register the same payment hash twice, at least until we've connected a
8732 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8733 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8734 assert_eq!(err, "Duplicate payment hash");
8735 } else { panic!(); }
8737 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8739 header: BlockHeader {
8741 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8742 merkle_root: TxMerkleNode::all_zeros(),
8743 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8747 connect_block(&nodes[1], &block);
8748 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8749 assert_eq!(err, "Duplicate payment hash");
8750 } else { panic!(); }
8752 // If we then connect the second block, we should be able to register the same payment hash
8753 // again (this time getting a new payment secret).
8754 block.header.prev_blockhash = block.header.block_hash();
8755 block.header.time += 1;
8756 connect_block(&nodes[1], &block);
8757 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8758 assert_ne!(payment_secret_1, our_payment_secret);
8761 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8762 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8763 check_added_monitors!(nodes[0], 1);
8764 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8765 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8766 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8767 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8769 // Note that after leaving the above scope we have no knowledge of any arguments or return
8770 // values from previous calls.
8771 expect_pending_htlcs_forwardable!(nodes[1]);
8772 let events = nodes[1].node.get_and_clear_pending_events();
8773 assert_eq!(events.len(), 1);
8775 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8776 assert!(payment_preimage.is_none());
8777 assert_eq!(payment_secret, our_payment_secret);
8778 // We don't actually have the payment preimage with which to claim this payment!
8780 _ => panic!("Unexpected event"),
8785 fn test_bad_secret_hash() {
8786 // Simple test of unregistered payment hash/invalid payment secret handling
8787 let chanmon_cfgs = create_chanmon_cfgs(2);
8788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8790 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8792 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8794 let random_payment_hash = PaymentHash([42; 32]);
8795 let random_payment_secret = PaymentSecret([43; 32]);
8796 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8797 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8799 // All the below cases should end up being handled exactly identically, so we macro the
8800 // resulting events.
8801 macro_rules! handle_unknown_invalid_payment_data {
8802 ($payment_hash: expr) => {
8803 check_added_monitors!(nodes[0], 1);
8804 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8805 let payment_event = SendEvent::from_event(events.pop().unwrap());
8806 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8807 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8809 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8810 // again to process the pending backwards-failure of the HTLC
8811 expect_pending_htlcs_forwardable!(nodes[1]);
8812 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8813 check_added_monitors!(nodes[1], 1);
8815 // We should fail the payment back
8816 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8817 match events.pop().unwrap() {
8818 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8819 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8820 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8822 _ => panic!("Unexpected event"),
8827 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8828 // Error data is the HTLC value (100,000) and current block height
8829 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8831 // Send a payment with the right payment hash but the wrong payment secret
8832 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8833 handle_unknown_invalid_payment_data!(our_payment_hash);
8834 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8836 // Send a payment with a random payment hash, but the right payment secret
8837 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8838 handle_unknown_invalid_payment_data!(random_payment_hash);
8839 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8841 // Send a payment with a random payment hash and random payment secret
8842 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8843 handle_unknown_invalid_payment_data!(random_payment_hash);
8844 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8848 fn test_update_err_monitor_lockdown() {
8849 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8850 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8851 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8854 // This scenario may happen in a watchtower setup, where watchtower process a block height
8855 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8856 // commitment at same time.
8858 let chanmon_cfgs = create_chanmon_cfgs(2);
8859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8861 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8863 // Create some initial channel
8864 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8865 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8867 // Rebalance the network to generate htlc in the two directions
8868 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8870 // Route a HTLC from node 0 to node 1 (but don't settle)
8871 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8873 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8874 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8875 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8876 let persister = test_utils::TestPersister::new();
8878 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8879 let mut w = test_utils::TestVecWriter(Vec::new());
8880 monitor.write(&mut w).unwrap();
8881 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8882 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8883 assert!(new_monitor == *monitor);
8884 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);
8885 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8888 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8889 let block = Block { header, txdata: vec![] };
8890 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8891 // transaction lock time requirements here.
8892 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8893 watchtower.chain_monitor.block_connected(&block, 200);
8895 // Try to update ChannelMonitor
8896 nodes[1].node.claim_funds(preimage);
8897 check_added_monitors!(nodes[1], 1);
8898 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8900 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8901 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8902 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8903 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8904 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8905 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8906 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8907 } else { assert!(false); }
8908 } else { assert!(false); };
8909 // Our local monitor is in-sync and hasn't processed yet timeout
8910 check_added_monitors!(nodes[0], 1);
8911 let events = nodes[0].node.get_and_clear_pending_events();
8912 assert_eq!(events.len(), 1);
8916 fn test_concurrent_monitor_claim() {
8917 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8918 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8919 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8920 // state N+1 confirms. Alice claims output from state N+1.
8922 let chanmon_cfgs = create_chanmon_cfgs(2);
8923 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8924 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8925 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8927 // Create some initial channel
8928 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8929 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8931 // Rebalance the network to generate htlc in the two directions
8932 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8934 // Route a HTLC from node 0 to node 1 (but don't settle)
8935 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8937 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8938 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8939 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8940 let persister = test_utils::TestPersister::new();
8941 let watchtower_alice = {
8942 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8943 let mut w = test_utils::TestVecWriter(Vec::new());
8944 monitor.write(&mut w).unwrap();
8945 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8946 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8947 assert!(new_monitor == *monitor);
8948 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);
8949 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8952 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8953 let block = Block { header, txdata: vec![] };
8954 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8955 // transaction lock time requirements here.
8956 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));
8957 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8959 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8961 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8962 assert_eq!(txn.len(), 2);
8966 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8967 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8968 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8969 let persister = test_utils::TestPersister::new();
8970 let watchtower_bob = {
8971 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8972 let mut w = test_utils::TestVecWriter(Vec::new());
8973 monitor.write(&mut w).unwrap();
8974 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8975 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8976 assert!(new_monitor == *monitor);
8977 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);
8978 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8981 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8982 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8984 // Route another payment to generate another update with still previous HTLC pending
8985 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8987 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8989 check_added_monitors!(nodes[1], 1);
8991 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8992 assert_eq!(updates.update_add_htlcs.len(), 1);
8993 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8994 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8995 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8996 // Watchtower Alice should already have seen the block and reject the update
8997 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8998 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8999 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
9000 } else { assert!(false); }
9001 } else { assert!(false); };
9002 // Our local monitor is in-sync and hasn't processed yet timeout
9003 check_added_monitors!(nodes[0], 1);
9005 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
9006 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9007 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
9009 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
9012 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9013 assert_eq!(txn.len(), 2);
9014 bob_state_y = txn[0].clone();
9018 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
9019 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9020 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);
9022 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9023 assert_eq!(htlc_txn.len(), 1);
9024 check_spends!(htlc_txn[0], bob_state_y);
9029 fn test_pre_lockin_no_chan_closed_update() {
9030 // Test that if a peer closes a channel in response to a funding_created message we don't
9031 // generate a channel update (as the channel cannot appear on chain without a funding_signed
9034 // Doing so would imply a channel monitor update before the initial channel monitor
9035 // registration, violating our API guarantees.
9037 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
9038 // then opening a second channel with the same funding output as the first (which is not
9039 // rejected because the first channel does not exist in the ChannelManager) and closing it
9040 // before receiving funding_signed.
9041 let chanmon_cfgs = create_chanmon_cfgs(2);
9042 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9043 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9044 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9046 // Create an initial channel
9047 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9048 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9049 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9050 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9051 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
9053 // Move the first channel through the funding flow...
9054 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9056 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9057 check_added_monitors!(nodes[0], 0);
9059 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9060 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
9061 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
9062 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
9063 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
9067 fn test_htlc_no_detection() {
9068 // This test is a mutation to underscore the detection logic bug we had
9069 // before #653. HTLC value routed is above the remaining balance, thus
9070 // inverting HTLC and `to_remote` output. HTLC will come second and
9071 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9072 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9073 // outputs order detection for correct spending children filtring.
9075 let chanmon_cfgs = create_chanmon_cfgs(2);
9076 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9077 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9078 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9080 // Create some initial channels
9081 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9083 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9084 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9085 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9086 assert_eq!(local_txn[0].input.len(), 1);
9087 assert_eq!(local_txn[0].output.len(), 3);
9088 check_spends!(local_txn[0], chan_1.3);
9090 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9091 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9092 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9093 // We deliberately connect the local tx twice as this should provoke a failure calling
9094 // this test before #653 fix.
9095 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);
9096 check_closed_broadcast!(nodes[0], true);
9097 check_added_monitors!(nodes[0], 1);
9098 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9099 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9101 let htlc_timeout = {
9102 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9103 assert_eq!(node_txn[1].input.len(), 1);
9104 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9105 check_spends!(node_txn[1], local_txn[0]);
9109 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9110 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9111 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9112 expect_payment_failed!(nodes[0], our_payment_hash, false);
9115 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9116 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9117 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9118 // Carol, Alice would be the upstream node, and Carol the downstream.)
9120 // Steps of the test:
9121 // 1) Alice sends a HTLC to Carol through Bob.
9122 // 2) Carol doesn't settle the HTLC.
9123 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9124 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9125 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9126 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9127 // 5) Carol release the preimage to Bob off-chain.
9128 // 6) Bob claims the offered output on the broadcasted commitment.
9129 let chanmon_cfgs = create_chanmon_cfgs(3);
9130 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9131 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9132 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9134 // Create some initial channels
9135 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9136 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9138 // Steps (1) and (2):
9139 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9140 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9142 // Check that Alice's commitment transaction now contains an output for this HTLC.
9143 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9144 check_spends!(alice_txn[0], chan_ab.3);
9145 assert_eq!(alice_txn[0].output.len(), 2);
9146 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9147 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9148 assert_eq!(alice_txn.len(), 2);
9150 // Steps (3) and (4):
9151 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9152 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9153 let mut force_closing_node = 0; // Alice force-closes
9154 let mut counterparty_node = 1; // Bob if Alice force-closes
9157 if !broadcast_alice {
9158 force_closing_node = 1;
9159 counterparty_node = 0;
9161 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9162 check_closed_broadcast!(nodes[force_closing_node], true);
9163 check_added_monitors!(nodes[force_closing_node], 1);
9164 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9165 if go_onchain_before_fulfill {
9166 let txn_to_broadcast = match broadcast_alice {
9167 true => alice_txn.clone(),
9168 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9170 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9171 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9172 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9173 if broadcast_alice {
9174 check_closed_broadcast!(nodes[1], true);
9175 check_added_monitors!(nodes[1], 1);
9176 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9178 assert_eq!(bob_txn.len(), 1);
9179 check_spends!(bob_txn[0], chan_ab.3);
9183 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9184 // process of removing the HTLC from their commitment transactions.
9185 nodes[2].node.claim_funds(payment_preimage);
9186 check_added_monitors!(nodes[2], 1);
9187 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9189 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9190 assert!(carol_updates.update_add_htlcs.is_empty());
9191 assert!(carol_updates.update_fail_htlcs.is_empty());
9192 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9193 assert!(carol_updates.update_fee.is_none());
9194 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9196 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9197 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9198 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9199 if !go_onchain_before_fulfill && broadcast_alice {
9200 let events = nodes[1].node.get_and_clear_pending_msg_events();
9201 assert_eq!(events.len(), 1);
9203 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9204 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9206 _ => panic!("Unexpected event"),
9209 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9210 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9211 // Carol<->Bob's updated commitment transaction info.
9212 check_added_monitors!(nodes[1], 2);
9214 let events = nodes[1].node.get_and_clear_pending_msg_events();
9215 assert_eq!(events.len(), 2);
9216 let bob_revocation = match events[0] {
9217 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9218 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9221 _ => panic!("Unexpected event"),
9223 let bob_updates = match events[1] {
9224 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9225 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9228 _ => panic!("Unexpected event"),
9231 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9232 check_added_monitors!(nodes[2], 1);
9233 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9234 check_added_monitors!(nodes[2], 1);
9236 let events = nodes[2].node.get_and_clear_pending_msg_events();
9237 assert_eq!(events.len(), 1);
9238 let carol_revocation = match events[0] {
9239 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9240 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9243 _ => panic!("Unexpected event"),
9245 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9246 check_added_monitors!(nodes[1], 1);
9248 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9249 // here's where we put said channel's commitment tx on-chain.
9250 let mut txn_to_broadcast = alice_txn.clone();
9251 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9252 if !go_onchain_before_fulfill {
9253 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9254 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9255 // If Bob was the one to force-close, he will have already passed these checks earlier.
9256 if broadcast_alice {
9257 check_closed_broadcast!(nodes[1], true);
9258 check_added_monitors!(nodes[1], 1);
9259 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9261 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9262 if broadcast_alice {
9263 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9264 // new block being connected. The ChannelManager being notified triggers a monitor update,
9265 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9266 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9268 assert_eq!(bob_txn.len(), 3);
9269 check_spends!(bob_txn[1], chan_ab.3);
9271 assert_eq!(bob_txn.len(), 2);
9272 check_spends!(bob_txn[0], chan_ab.3);
9277 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9278 // broadcasted commitment transaction.
9280 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9281 if go_onchain_before_fulfill {
9282 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9283 assert_eq!(bob_txn.len(), 2);
9285 let script_weight = match broadcast_alice {
9286 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9287 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9289 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9290 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9291 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9292 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9293 if broadcast_alice && !go_onchain_before_fulfill {
9294 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9295 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9297 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9298 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9304 fn test_onchain_htlc_settlement_after_close() {
9305 do_test_onchain_htlc_settlement_after_close(true, true);
9306 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9307 do_test_onchain_htlc_settlement_after_close(true, false);
9308 do_test_onchain_htlc_settlement_after_close(false, false);
9312 fn test_duplicate_chan_id() {
9313 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9314 // already open we reject it and keep the old channel.
9316 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9317 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9318 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9319 // updating logic for the existing channel.
9320 let chanmon_cfgs = create_chanmon_cfgs(2);
9321 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9322 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9323 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9325 // Create an initial channel
9326 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9327 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9328 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9329 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9331 // Try to create a second channel with the same temporary_channel_id as the first and check
9332 // that it is rejected.
9333 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9335 let events = nodes[1].node.get_and_clear_pending_msg_events();
9336 assert_eq!(events.len(), 1);
9338 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9339 // Technically, at this point, nodes[1] would be justified in thinking both the
9340 // first (valid) and second (invalid) channels are closed, given they both have
9341 // the same non-temporary channel_id. However, currently we do not, so we just
9342 // move forward with it.
9343 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9344 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9346 _ => panic!("Unexpected event"),
9350 // Move the first channel through the funding flow...
9351 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9353 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9354 check_added_monitors!(nodes[0], 0);
9356 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9357 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9359 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9360 assert_eq!(added_monitors.len(), 1);
9361 assert_eq!(added_monitors[0].0, funding_output);
9362 added_monitors.clear();
9364 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9366 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9367 let channel_id = funding_outpoint.to_channel_id();
9369 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9372 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9373 // Technically this is allowed by the spec, but we don't support it and there's little reason
9374 // to. Still, it shouldn't cause any other issues.
9375 open_chan_msg.temporary_channel_id = channel_id;
9376 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9378 let events = nodes[1].node.get_and_clear_pending_msg_events();
9379 assert_eq!(events.len(), 1);
9381 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9382 // Technically, at this point, nodes[1] would be justified in thinking both
9383 // channels are closed, but currently we do not, so we just move forward with it.
9384 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9385 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9387 _ => panic!("Unexpected event"),
9391 // Now try to create a second channel which has a duplicate funding output.
9392 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9393 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9394 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
9395 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9396 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9398 let funding_created = {
9399 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9400 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9401 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9402 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9403 // channelmanager in a possibly nonsense state instead).
9404 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9405 let logger = test_utils::TestLogger::new();
9406 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9408 check_added_monitors!(nodes[0], 0);
9409 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9410 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9411 // still needs to be cleared here.
9412 check_added_monitors!(nodes[1], 1);
9414 // ...still, nodes[1] will reject the duplicate channel.
9416 let events = nodes[1].node.get_and_clear_pending_msg_events();
9417 assert_eq!(events.len(), 1);
9419 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9420 // Technically, at this point, nodes[1] would be justified in thinking both
9421 // channels are closed, but currently we do not, so we just move forward with it.
9422 assert_eq!(msg.channel_id, channel_id);
9423 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9425 _ => panic!("Unexpected event"),
9429 // finally, finish creating the original channel and send a payment over it to make sure
9430 // everything is functional.
9431 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9433 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9434 assert_eq!(added_monitors.len(), 1);
9435 assert_eq!(added_monitors[0].0, funding_output);
9436 added_monitors.clear();
9439 let events_4 = nodes[0].node.get_and_clear_pending_events();
9440 assert_eq!(events_4.len(), 0);
9441 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9442 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9444 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9445 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9446 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9448 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9452 fn test_error_chans_closed() {
9453 // Test that we properly handle error messages, closing appropriate channels.
9455 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9456 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9457 // we can test various edge cases around it to ensure we don't regress.
9458 let chanmon_cfgs = create_chanmon_cfgs(3);
9459 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9460 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9461 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9463 // Create some initial channels
9464 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9465 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9466 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9468 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9469 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9470 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9472 // Closing a channel from a different peer has no effect
9473 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9474 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9476 // Closing one channel doesn't impact others
9477 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9478 check_added_monitors!(nodes[0], 1);
9479 check_closed_broadcast!(nodes[0], false);
9480 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9481 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9482 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9483 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);
9484 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);
9486 // A null channel ID should close all channels
9487 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9488 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9489 check_added_monitors!(nodes[0], 2);
9490 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9491 let events = nodes[0].node.get_and_clear_pending_msg_events();
9492 assert_eq!(events.len(), 2);
9494 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9495 assert_eq!(msg.contents.flags & 2, 2);
9497 _ => panic!("Unexpected event"),
9500 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9501 assert_eq!(msg.contents.flags & 2, 2);
9503 _ => panic!("Unexpected event"),
9505 // Note that at this point users of a standard PeerHandler will end up calling
9506 // peer_disconnected with no_connection_possible set to false, duplicating the
9507 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9508 // users with their own peer handling logic. We duplicate the call here, however.
9509 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9510 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9512 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9513 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9514 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9518 fn test_invalid_funding_tx() {
9519 // Test that we properly handle invalid funding transactions sent to us from a peer.
9521 // Previously, all other major lightning implementations had failed to properly sanitize
9522 // funding transactions from their counterparties, leading to a multi-implementation critical
9523 // security vulnerability (though we always sanitized properly, we've previously had
9524 // un-released crashes in the sanitization process).
9526 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9527 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9528 // gave up on it. We test this here by generating such a transaction.
9529 let chanmon_cfgs = create_chanmon_cfgs(2);
9530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9532 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9534 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9535 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9536 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9538 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9540 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9541 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9542 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9544 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9545 let wit_program_script: Script = wit_program.into();
9546 for output in tx.output.iter_mut() {
9547 // Make the confirmed funding transaction have a bogus script_pubkey
9548 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9551 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9552 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()));
9553 check_added_monitors!(nodes[1], 1);
9555 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()));
9556 check_added_monitors!(nodes[0], 1);
9558 let events_1 = nodes[0].node.get_and_clear_pending_events();
9559 assert_eq!(events_1.len(), 0);
9561 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9562 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9563 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9565 let expected_err = "funding tx had wrong script/value or output index";
9566 confirm_transaction_at(&nodes[1], &tx, 1);
9567 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9568 check_added_monitors!(nodes[1], 1);
9569 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9570 assert_eq!(events_2.len(), 1);
9571 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9572 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9573 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9574 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9575 } else { panic!(); }
9576 } else { panic!(); }
9577 assert_eq!(nodes[1].node.list_channels().len(), 0);
9579 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9580 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9581 // as its not 32 bytes long.
9582 let mut spend_tx = Transaction {
9583 version: 2i32, lock_time: PackedLockTime::ZERO,
9584 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9585 previous_output: BitcoinOutPoint {
9589 script_sig: Script::new(),
9590 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9591 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9593 output: vec![TxOut {
9595 script_pubkey: Script::new(),
9598 check_spends!(spend_tx, tx);
9599 mine_transaction(&nodes[1], &spend_tx);
9602 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9603 // In the first version of the chain::Confirm interface, after a refactor was made to not
9604 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9605 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9606 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9607 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9608 // spending transaction until height N+1 (or greater). This was due to the way
9609 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9610 // spending transaction at the height the input transaction was confirmed at, not whether we
9611 // should broadcast a spending transaction at the current height.
9612 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9613 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9614 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9615 // until we learned about an additional block.
9617 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9618 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9619 let chanmon_cfgs = create_chanmon_cfgs(3);
9620 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9621 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9622 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9623 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9625 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9626 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9627 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9628 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9629 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9631 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9632 check_closed_broadcast!(nodes[1], true);
9633 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9634 check_added_monitors!(nodes[1], 1);
9635 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9636 assert_eq!(node_txn.len(), 1);
9638 let conf_height = nodes[1].best_block_info().1;
9639 if !test_height_before_timelock {
9640 connect_blocks(&nodes[1], 24 * 6);
9642 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9643 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9644 if test_height_before_timelock {
9645 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9646 // generate any events or broadcast any transactions
9647 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9648 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9650 // We should broadcast an HTLC transaction spending our funding transaction first
9651 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9652 assert_eq!(spending_txn.len(), 2);
9653 assert_eq!(spending_txn[0], node_txn[0]);
9654 check_spends!(spending_txn[1], node_txn[0]);
9655 // We should also generate a SpendableOutputs event with the to_self output (as its
9657 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9658 assert_eq!(descriptor_spend_txn.len(), 1);
9660 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9661 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9662 // additional block built on top of the current chain.
9663 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9664 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9665 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 }]);
9666 check_added_monitors!(nodes[1], 1);
9668 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9669 assert!(updates.update_add_htlcs.is_empty());
9670 assert!(updates.update_fulfill_htlcs.is_empty());
9671 assert_eq!(updates.update_fail_htlcs.len(), 1);
9672 assert!(updates.update_fail_malformed_htlcs.is_empty());
9673 assert!(updates.update_fee.is_none());
9674 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9675 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9676 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9681 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9682 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9683 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9687 fn test_forwardable_regen() {
9688 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9689 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9691 // We test it for both payment receipt and payment forwarding.
9693 let chanmon_cfgs = create_chanmon_cfgs(3);
9694 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9695 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9696 let persister: test_utils::TestPersister;
9697 let new_chain_monitor: test_utils::TestChainMonitor;
9698 let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9699 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9700 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9701 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9703 // First send a payment to nodes[1]
9704 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9705 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9706 check_added_monitors!(nodes[0], 1);
9708 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9709 assert_eq!(events.len(), 1);
9710 let payment_event = SendEvent::from_event(events.pop().unwrap());
9711 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9712 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9714 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9716 // Next send a payment which is forwarded by nodes[1]
9717 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9718 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9719 check_added_monitors!(nodes[0], 1);
9721 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9722 assert_eq!(events.len(), 1);
9723 let payment_event = SendEvent::from_event(events.pop().unwrap());
9724 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9725 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9727 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9729 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9731 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9732 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9733 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9735 let nodes_1_serialized = nodes[1].node.encode();
9736 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9737 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9738 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9739 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9741 persister = test_utils::TestPersister::new();
9742 let keys_manager = &chanmon_cfgs[1].keys_manager;
9743 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[1].chain_source), nodes[1].tx_broadcaster.clone(), nodes[1].logger, node_cfgs[1].fee_estimator, &persister, keys_manager);
9744 nodes[1].chain_monitor = &new_chain_monitor;
9746 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9747 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9748 &mut chan_0_monitor_read, keys_manager).unwrap();
9749 assert!(chan_0_monitor_read.is_empty());
9750 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9751 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9752 &mut chan_1_monitor_read, keys_manager).unwrap();
9753 assert!(chan_1_monitor_read.is_empty());
9755 let mut nodes_1_read = &nodes_1_serialized[..];
9756 let (_, nodes_1_deserialized_tmp) = {
9757 let mut channel_monitors = HashMap::new();
9758 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9759 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9760 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9761 default_config: UserConfig::default(),
9763 fee_estimator: node_cfgs[1].fee_estimator,
9764 chain_monitor: nodes[1].chain_monitor,
9765 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9766 logger: nodes[1].logger,
9770 nodes_1_deserialized = nodes_1_deserialized_tmp;
9771 assert!(nodes_1_read.is_empty());
9773 assert_eq!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
9774 ChannelMonitorUpdateStatus::Completed);
9775 assert_eq!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor),
9776 ChannelMonitorUpdateStatus::Completed);
9777 nodes[1].node = &nodes_1_deserialized;
9778 check_added_monitors!(nodes[1], 2);
9780 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9781 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9782 // the commitment state.
9783 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9785 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9787 expect_pending_htlcs_forwardable!(nodes[1]);
9788 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9789 check_added_monitors!(nodes[1], 1);
9791 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9792 assert_eq!(events.len(), 1);
9793 let payment_event = SendEvent::from_event(events.pop().unwrap());
9794 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9795 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9796 expect_pending_htlcs_forwardable!(nodes[2]);
9797 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9799 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9800 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9803 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9804 let chanmon_cfgs = create_chanmon_cfgs(2);
9805 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9806 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9807 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9809 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9811 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9812 .with_features(channelmanager::provided_invoice_features());
9813 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9815 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9818 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9819 check_added_monitors!(nodes[0], 1);
9820 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9821 assert_eq!(events.len(), 1);
9822 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9823 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9824 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9826 expect_pending_htlcs_forwardable!(nodes[1]);
9827 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9830 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9831 check_added_monitors!(nodes[0], 1);
9832 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9833 assert_eq!(events.len(), 1);
9834 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9835 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9836 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9837 // At this point, nodes[1] would notice it has too much value for the payment. It will
9838 // assume the second is a privacy attack (no longer particularly relevant
9839 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9840 // the first HTLC delivered above.
9843 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9844 nodes[1].node.process_pending_htlc_forwards();
9846 if test_for_second_fail_panic {
9847 // Now we go fail back the first HTLC from the user end.
9848 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9850 let expected_destinations = vec![
9851 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9852 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9854 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9855 nodes[1].node.process_pending_htlc_forwards();
9857 check_added_monitors!(nodes[1], 1);
9858 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9859 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9861 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9862 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9863 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9865 let failure_events = nodes[0].node.get_and_clear_pending_events();
9866 assert_eq!(failure_events.len(), 2);
9867 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9868 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9870 // Let the second HTLC fail and claim the first
9871 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9872 nodes[1].node.process_pending_htlc_forwards();
9874 check_added_monitors!(nodes[1], 1);
9875 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9876 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9877 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9879 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9881 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9886 fn test_dup_htlc_second_fail_panic() {
9887 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9888 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9889 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9890 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9891 do_test_dup_htlc_second_rejected(true);
9895 fn test_dup_htlc_second_rejected() {
9896 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9897 // simply reject the second HTLC but are still able to claim the first HTLC.
9898 do_test_dup_htlc_second_rejected(false);
9902 fn test_inconsistent_mpp_params() {
9903 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9904 // such HTLC and allow the second to stay.
9905 let chanmon_cfgs = create_chanmon_cfgs(4);
9906 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9907 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9908 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9910 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9911 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9912 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9913 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9915 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9916 .with_features(channelmanager::provided_invoice_features());
9917 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9918 assert_eq!(route.paths.len(), 2);
9919 route.paths.sort_by(|path_a, _| {
9920 // Sort the path so that the path through nodes[1] comes first
9921 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9922 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9924 let payment_params_opt = Some(payment_params);
9926 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9928 let cur_height = nodes[0].best_block_info().1;
9929 let payment_id = PaymentId([42; 32]);
9931 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).unwrap();
9932 check_added_monitors!(nodes[0], 1);
9934 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9935 assert_eq!(events.len(), 1);
9936 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9938 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9941 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).unwrap();
9942 check_added_monitors!(nodes[0], 1);
9944 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9945 assert_eq!(events.len(), 1);
9946 let payment_event = SendEvent::from_event(events.pop().unwrap());
9948 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9949 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9951 expect_pending_htlcs_forwardable!(nodes[2]);
9952 check_added_monitors!(nodes[2], 1);
9954 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9955 assert_eq!(events.len(), 1);
9956 let payment_event = SendEvent::from_event(events.pop().unwrap());
9958 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9959 check_added_monitors!(nodes[3], 0);
9960 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9962 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9963 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9964 // post-payment_secrets) and fail back the new HTLC.
9966 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9967 nodes[3].node.process_pending_htlc_forwards();
9968 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9969 nodes[3].node.process_pending_htlc_forwards();
9971 check_added_monitors!(nodes[3], 1);
9973 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9974 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9975 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9977 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 }]);
9978 check_added_monitors!(nodes[2], 1);
9980 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9981 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9982 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9984 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9986 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).unwrap();
9987 check_added_monitors!(nodes[0], 1);
9989 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9990 assert_eq!(events.len(), 1);
9991 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9993 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9997 fn test_keysend_payments_to_public_node() {
9998 let chanmon_cfgs = create_chanmon_cfgs(2);
9999 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10000 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10001 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10003 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10004 let network_graph = nodes[0].network_graph;
10005 let payer_pubkey = nodes[0].node.get_our_node_id();
10006 let payee_pubkey = nodes[1].node.get_our_node_id();
10007 let route_params = RouteParameters {
10008 payment_params: PaymentParameters::for_keysend(payee_pubkey),
10009 final_value_msat: 10000,
10010 final_cltv_expiry_delta: 40,
10012 let scorer = test_utils::TestScorer::with_penalty(0);
10013 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10014 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
10016 let test_preimage = PaymentPreimage([42; 32]);
10017 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
10018 check_added_monitors!(nodes[0], 1);
10019 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10020 assert_eq!(events.len(), 1);
10021 let event = events.pop().unwrap();
10022 let path = vec![&nodes[1]];
10023 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10024 claim_payment(&nodes[0], &path, test_preimage);
10028 fn test_keysend_payments_to_private_node() {
10029 let chanmon_cfgs = create_chanmon_cfgs(2);
10030 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10031 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10032 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10034 let payer_pubkey = nodes[0].node.get_our_node_id();
10035 let payee_pubkey = nodes[1].node.get_our_node_id();
10036 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10037 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10039 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
10040 let route_params = RouteParameters {
10041 payment_params: PaymentParameters::for_keysend(payee_pubkey),
10042 final_value_msat: 10000,
10043 final_cltv_expiry_delta: 40,
10045 let network_graph = nodes[0].network_graph;
10046 let first_hops = nodes[0].node.list_usable_channels();
10047 let scorer = test_utils::TestScorer::with_penalty(0);
10048 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10049 let route = find_route(
10050 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10051 nodes[0].logger, &scorer, &random_seed_bytes
10054 let test_preimage = PaymentPreimage([42; 32]);
10055 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
10056 check_added_monitors!(nodes[0], 1);
10057 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10058 assert_eq!(events.len(), 1);
10059 let event = events.pop().unwrap();
10060 let path = vec![&nodes[1]];
10061 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10062 claim_payment(&nodes[0], &path, test_preimage);
10066 fn test_double_partial_claim() {
10067 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
10068 // time out, the sender resends only some of the MPP parts, then the user processes the
10069 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10071 let chanmon_cfgs = create_chanmon_cfgs(4);
10072 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10073 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10074 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10076 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10077 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10078 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10079 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10081 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10082 assert_eq!(route.paths.len(), 2);
10083 route.paths.sort_by(|path_a, _| {
10084 // Sort the path so that the path through nodes[1] comes first
10085 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10086 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10089 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10090 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10091 // amount of time to respond to.
10093 // Connect some blocks to time out the payment
10094 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10095 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10097 let failed_destinations = vec![
10098 HTLCDestination::FailedPayment { payment_hash },
10099 HTLCDestination::FailedPayment { payment_hash },
10101 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10103 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10105 // nodes[1] now retries one of the two paths...
10106 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10107 check_added_monitors!(nodes[0], 2);
10109 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10110 assert_eq!(events.len(), 2);
10111 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10113 // At this point nodes[3] has received one half of the payment, and the user goes to handle
10114 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10115 nodes[3].node.claim_funds(payment_preimage);
10116 check_added_monitors!(nodes[3], 0);
10117 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10120 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10121 // Test what happens if a node receives an MPP payment, claims it, but crashes before
10122 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10123 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10124 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10125 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10126 // not have the preimage tied to the still-pending HTLC.
10128 // To get to the correct state, on startup we should propagate the preimage to the
10129 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10130 // receiving the preimage without a state update.
10132 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10133 // definitely claimed.
10134 let chanmon_cfgs = create_chanmon_cfgs(4);
10135 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10136 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10138 let persister: test_utils::TestPersister;
10139 let new_chain_monitor: test_utils::TestChainMonitor;
10140 let nodes_3_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10142 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10144 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10145 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10146 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
10147 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
10149 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10150 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10151 assert_eq!(route.paths.len(), 2);
10152 route.paths.sort_by(|path_a, _| {
10153 // Sort the path so that the path through nodes[1] comes first
10154 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10155 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10158 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10159 check_added_monitors!(nodes[0], 2);
10161 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10162 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10163 assert_eq!(send_events.len(), 2);
10164 do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
10165 do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[1].clone(), true, false, None);
10167 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10168 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10169 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10170 if !persist_both_monitors {
10171 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10172 if outpoint.to_channel_id() == chan_id_not_persisted {
10173 assert!(original_monitor.0.is_empty());
10174 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10179 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10180 nodes[3].node.write(&mut original_manager).unwrap();
10182 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10184 nodes[3].node.claim_funds(payment_preimage);
10185 check_added_monitors!(nodes[3], 2);
10186 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10188 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10189 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10190 // with the old ChannelManager.
10191 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10192 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10193 if outpoint.to_channel_id() == chan_id_persisted {
10194 assert!(updated_monitor.0.is_empty());
10195 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10198 // If `persist_both_monitors` is set, get the second monitor here as well
10199 if persist_both_monitors {
10200 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10201 if outpoint.to_channel_id() == chan_id_not_persisted {
10202 assert!(original_monitor.0.is_empty());
10203 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10208 // Now restart nodes[3].
10209 persister = test_utils::TestPersister::new();
10210 let keys_manager = &chanmon_cfgs[3].keys_manager;
10211 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[3].chain_source), nodes[3].tx_broadcaster.clone(), nodes[3].logger, node_cfgs[3].fee_estimator, &persister, keys_manager);
10212 nodes[3].chain_monitor = &new_chain_monitor;
10213 let mut monitors = Vec::new();
10214 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10215 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10216 monitors.push(deserialized_monitor);
10219 let config = UserConfig::default();
10220 nodes_3_deserialized = {
10221 let mut channel_monitors = HashMap::new();
10222 for monitor in monitors.iter_mut() {
10223 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10225 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10226 default_config: config,
10228 fee_estimator: node_cfgs[3].fee_estimator,
10229 chain_monitor: nodes[3].chain_monitor,
10230 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10231 logger: nodes[3].logger,
10235 nodes[3].node = &nodes_3_deserialized;
10237 for monitor in monitors {
10238 // On startup the preimage should have been copied into the non-persisted monitor:
10239 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10240 assert_eq!(nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor),
10241 ChannelMonitorUpdateStatus::Completed);
10243 check_added_monitors!(nodes[3], 2);
10245 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10246 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10248 // During deserialization, we should have closed one channel and broadcast its latest
10249 // commitment transaction. We should also still have the original PaymentReceived event we
10250 // never finished processing.
10251 let events = nodes[3].node.get_and_clear_pending_events();
10252 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10253 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10254 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10255 if persist_both_monitors {
10256 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10259 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10260 // ChannelManager prior to handling the original one.
10261 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10262 events[if persist_both_monitors { 3 } else { 2 }]
10264 assert_eq!(payment_hash, our_payment_hash);
10265 } else { panic!(); }
10267 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10268 if !persist_both_monitors {
10269 // If one of the two channels is still live, reveal the payment preimage over it.
10271 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10272 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10273 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10274 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10276 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10277 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10278 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10280 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10282 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10283 // claim should fly.
10284 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10285 check_added_monitors!(nodes[3], 1);
10286 assert_eq!(ds_msgs.len(), 2);
10287 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10289 let cs_updates = match ds_msgs[0] {
10290 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10291 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10292 check_added_monitors!(nodes[2], 1);
10293 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10294 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10295 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10301 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10302 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10303 expect_payment_sent!(nodes[0], payment_preimage);
10308 fn test_partial_claim_before_restart() {
10309 do_test_partial_claim_before_restart(false);
10310 do_test_partial_claim_before_restart(true);
10313 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10314 #[derive(Clone, Copy, PartialEq)]
10315 enum ExposureEvent {
10316 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10318 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10320 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10321 AtUpdateFeeOutbound,
10324 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10325 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10328 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10329 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10330 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10331 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10332 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10333 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10334 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10335 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10337 let chanmon_cfgs = create_chanmon_cfgs(2);
10338 let mut config = test_default_channel_config();
10339 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10342 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10344 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10345 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10346 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10347 open_channel.max_accepted_htlcs = 60;
10349 open_channel.dust_limit_satoshis = 546;
10351 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
10352 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10353 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
10355 let opt_anchors = false;
10357 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10360 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10361 chan.holder_dust_limit_satoshis = 546;
10365 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10366 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()));
10367 check_added_monitors!(nodes[1], 1);
10369 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()));
10370 check_added_monitors!(nodes[0], 1);
10372 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10373 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10374 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10376 let dust_buffer_feerate = {
10377 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10378 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10379 chan.get_dust_buffer_feerate(None) as u64
10381 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;
10382 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10384 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;
10385 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10387 let dust_htlc_on_counterparty_tx: u64 = 25;
10388 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10391 if dust_outbound_balance {
10392 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10393 // Outbound dust balance: 4372 sats
10394 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10395 for i in 0..dust_outbound_htlc_on_holder_tx {
10396 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10397 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10400 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10401 // Inbound dust balance: 4372 sats
10402 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10403 for _ in 0..dust_inbound_htlc_on_holder_tx {
10404 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10408 if dust_outbound_balance {
10409 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10410 // Outbound dust balance: 5000 sats
10411 for i in 0..dust_htlc_on_counterparty_tx {
10412 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10413 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10416 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10417 // Inbound dust balance: 5000 sats
10418 for _ in 0..dust_htlc_on_counterparty_tx {
10419 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10424 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10425 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10426 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 });
10427 let mut config = UserConfig::default();
10428 // With default dust exposure: 5000 sats
10430 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10431 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10432 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), 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)));
10434 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), 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)));
10436 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10437 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 });
10438 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10439 check_added_monitors!(nodes[1], 1);
10440 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10441 assert_eq!(events.len(), 1);
10442 let payment_event = SendEvent::from_event(events.remove(0));
10443 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10444 // With default dust exposure: 5000 sats
10446 // Outbound dust balance: 6399 sats
10447 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10448 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10449 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);
10451 // Outbound dust balance: 5200 sats
10452 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);
10454 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10455 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10456 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10458 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10459 *feerate_lock = *feerate_lock * 10;
10461 nodes[0].node.timer_tick_occurred();
10462 check_added_monitors!(nodes[0], 1);
10463 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);
10466 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10467 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10468 added_monitors.clear();
10472 fn test_max_dust_htlc_exposure() {
10473 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10474 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10475 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10476 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10477 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10478 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10479 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10480 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10481 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10482 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10483 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10484 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10488 fn test_non_final_funding_tx() {
10489 let chanmon_cfgs = create_chanmon_cfgs(2);
10490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10492 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10494 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10495 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10496 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
10497 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10498 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
10500 let best_height = nodes[0].node.best_block.read().unwrap().height();
10502 let chan_id = *nodes[0].network_chan_count.borrow();
10503 let events = nodes[0].node.get_and_clear_pending_events();
10504 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10505 assert_eq!(events.len(), 1);
10506 let mut tx = match events[0] {
10507 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10508 // Timelock the transaction _beyond_ the best client height + 2.
10509 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10510 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10513 _ => panic!("Unexpected event"),
10515 // Transaction should fail as it's evaluated as non-final for propagation.
10516 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10517 Err(APIError::APIMisuseError { err }) => {
10518 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10523 // However, transaction should be accepted if it's in a +2 headroom from best block.
10524 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10525 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10526 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());