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 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2958 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 }]);
2959 check_added_monitors!(nodes[1], 1);
2960 let events = nodes[1].node.get_and_clear_pending_msg_events();
2961 assert_eq!(events.len(), 1);
2963 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, .. } } => {
2964 assert!(update_add_htlcs.is_empty());
2965 assert!(!update_fail_htlcs.is_empty());
2966 assert!(update_fulfill_htlcs.is_empty());
2967 assert!(update_fail_malformed_htlcs.is_empty());
2968 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2970 _ => panic!("Unexpected event"),
2973 // Broadcast legit commitment tx from B on A's chain
2974 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2975 check_spends!(commitment_tx[0], chan_1.3);
2977 mine_transaction(&nodes[0], &commitment_tx[0]);
2978 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2980 check_closed_broadcast!(nodes[0], true);
2981 check_added_monitors!(nodes[0], 1);
2982 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2983 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2984 assert_eq!(node_txn.len(), 2);
2985 check_spends!(node_txn[0], chan_1.3);
2986 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2987 check_spends!(node_txn[1], commitment_tx[0]);
2988 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2992 fn test_htlc_on_chain_timeout() {
2993 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2994 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2995 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2999 fn test_simple_commitment_revoked_fail_backward() {
3000 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3001 // and fail backward accordingly.
3003 let chanmon_cfgs = create_chanmon_cfgs(3);
3004 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3005 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3006 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3008 // Create some initial channels
3009 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3010 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3012 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3013 // Get the will-be-revoked local txn from nodes[2]
3014 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3015 // Revoke the old state
3016 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3018 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3020 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3021 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3022 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3023 check_added_monitors!(nodes[1], 1);
3024 check_closed_broadcast!(nodes[1], true);
3026 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3027 check_added_monitors!(nodes[1], 1);
3028 let events = nodes[1].node.get_and_clear_pending_msg_events();
3029 assert_eq!(events.len(), 1);
3031 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3032 assert!(update_add_htlcs.is_empty());
3033 assert_eq!(update_fail_htlcs.len(), 1);
3034 assert!(update_fulfill_htlcs.is_empty());
3035 assert!(update_fail_malformed_htlcs.is_empty());
3036 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3038 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3039 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3040 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3042 _ => panic!("Unexpected event"),
3046 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3047 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3048 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3049 // commitment transaction anymore.
3050 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3051 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3052 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3053 // technically disallowed and we should probably handle it reasonably.
3054 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3055 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3057 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3058 // commitment_signed (implying it will be in the latest remote commitment transaction).
3059 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3060 // and once they revoke the previous commitment transaction (allowing us to send a new
3061 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3062 let chanmon_cfgs = create_chanmon_cfgs(3);
3063 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3064 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3065 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3067 // Create some initial channels
3068 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3069 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3071 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3072 // Get the will-be-revoked local txn from nodes[2]
3073 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3074 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3075 // Revoke the old state
3076 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3078 let value = if use_dust {
3079 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3080 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3081 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3084 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3085 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3086 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3088 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3089 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3090 check_added_monitors!(nodes[2], 1);
3091 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3092 assert!(updates.update_add_htlcs.is_empty());
3093 assert!(updates.update_fulfill_htlcs.is_empty());
3094 assert!(updates.update_fail_malformed_htlcs.is_empty());
3095 assert_eq!(updates.update_fail_htlcs.len(), 1);
3096 assert!(updates.update_fee.is_none());
3097 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3098 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3099 // Drop the last RAA from 3 -> 2
3101 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3102 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3103 check_added_monitors!(nodes[2], 1);
3104 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3105 assert!(updates.update_add_htlcs.is_empty());
3106 assert!(updates.update_fulfill_htlcs.is_empty());
3107 assert!(updates.update_fail_malformed_htlcs.is_empty());
3108 assert_eq!(updates.update_fail_htlcs.len(), 1);
3109 assert!(updates.update_fee.is_none());
3110 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3111 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3112 check_added_monitors!(nodes[1], 1);
3113 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3114 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3115 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3116 check_added_monitors!(nodes[2], 1);
3118 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3119 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3120 check_added_monitors!(nodes[2], 1);
3121 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3122 assert!(updates.update_add_htlcs.is_empty());
3123 assert!(updates.update_fulfill_htlcs.is_empty());
3124 assert!(updates.update_fail_malformed_htlcs.is_empty());
3125 assert_eq!(updates.update_fail_htlcs.len(), 1);
3126 assert!(updates.update_fee.is_none());
3127 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3128 // At this point first_payment_hash has dropped out of the latest two commitment
3129 // transactions that nodes[1] is tracking...
3130 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3131 check_added_monitors!(nodes[1], 1);
3132 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3133 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3134 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3135 check_added_monitors!(nodes[2], 1);
3137 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3138 // on nodes[2]'s RAA.
3139 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3140 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3141 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3142 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3143 check_added_monitors!(nodes[1], 0);
3146 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3147 // One monitor for the new revocation preimage, no second on as we won't generate a new
3148 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3149 check_added_monitors!(nodes[1], 1);
3150 let events = nodes[1].node.get_and_clear_pending_events();
3151 assert_eq!(events.len(), 2);
3153 Event::PendingHTLCsForwardable { .. } => { },
3154 _ => panic!("Unexpected event"),
3157 Event::HTLCHandlingFailed { .. } => { },
3158 _ => panic!("Unexpected event"),
3160 // Deliberately don't process the pending fail-back so they all fail back at once after
3161 // block connection just like the !deliver_bs_raa case
3164 let mut failed_htlcs = HashSet::new();
3165 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3167 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3168 check_added_monitors!(nodes[1], 1);
3169 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3170 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3172 let events = nodes[1].node.get_and_clear_pending_events();
3173 assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3175 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3176 _ => panic!("Unexepected event"),
3179 Event::PaymentPathFailed { ref payment_hash, .. } => {
3180 assert_eq!(*payment_hash, fourth_payment_hash);
3182 _ => panic!("Unexpected event"),
3184 if !deliver_bs_raa {
3186 Event::PaymentFailed { ref payment_hash, .. } => {
3187 assert_eq!(*payment_hash, fourth_payment_hash);
3189 _ => panic!("Unexpected event"),
3192 Event::PendingHTLCsForwardable { .. } => { },
3193 _ => panic!("Unexpected event"),
3196 nodes[1].node.process_pending_htlc_forwards();
3197 check_added_monitors!(nodes[1], 1);
3199 let events = nodes[1].node.get_and_clear_pending_msg_events();
3200 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3201 match events[if deliver_bs_raa { 1 } else { 0 }] {
3202 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3203 _ => panic!("Unexpected event"),
3205 match events[if deliver_bs_raa { 2 } else { 1 }] {
3206 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3207 assert_eq!(channel_id, chan_2.2);
3208 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3210 _ => panic!("Unexpected event"),
3214 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, .. } } => {
3215 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3216 assert_eq!(update_add_htlcs.len(), 1);
3217 assert!(update_fulfill_htlcs.is_empty());
3218 assert!(update_fail_htlcs.is_empty());
3219 assert!(update_fail_malformed_htlcs.is_empty());
3221 _ => panic!("Unexpected event"),
3224 match events[if deliver_bs_raa { 3 } else { 2 }] {
3225 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, .. } } => {
3226 assert!(update_add_htlcs.is_empty());
3227 assert_eq!(update_fail_htlcs.len(), 3);
3228 assert!(update_fulfill_htlcs.is_empty());
3229 assert!(update_fail_malformed_htlcs.is_empty());
3230 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3232 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3233 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3234 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3236 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3238 let events = nodes[0].node.get_and_clear_pending_events();
3239 assert_eq!(events.len(), 3);
3241 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3242 assert!(failed_htlcs.insert(payment_hash.0));
3243 // If we delivered B's RAA we got an unknown preimage error, not something
3244 // that we should update our routing table for.
3245 if !deliver_bs_raa {
3246 assert!(network_update.is_some());
3249 _ => panic!("Unexpected event"),
3252 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3253 assert!(failed_htlcs.insert(payment_hash.0));
3254 assert!(network_update.is_some());
3256 _ => panic!("Unexpected event"),
3259 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3260 assert!(failed_htlcs.insert(payment_hash.0));
3261 assert!(network_update.is_some());
3263 _ => panic!("Unexpected event"),
3266 _ => panic!("Unexpected event"),
3269 assert!(failed_htlcs.contains(&first_payment_hash.0));
3270 assert!(failed_htlcs.contains(&second_payment_hash.0));
3271 assert!(failed_htlcs.contains(&third_payment_hash.0));
3275 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3276 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3277 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3278 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3279 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3283 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3284 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3285 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3286 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3287 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3291 fn fail_backward_pending_htlc_upon_channel_failure() {
3292 let chanmon_cfgs = create_chanmon_cfgs(2);
3293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3295 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3296 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());
3298 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3300 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3301 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3302 check_added_monitors!(nodes[0], 1);
3304 let payment_event = {
3305 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3306 assert_eq!(events.len(), 1);
3307 SendEvent::from_event(events.remove(0))
3309 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3310 assert_eq!(payment_event.msgs.len(), 1);
3313 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3314 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3316 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3317 check_added_monitors!(nodes[0], 0);
3319 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3322 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3324 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3326 let secp_ctx = Secp256k1::new();
3327 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3328 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3329 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3330 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3331 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3333 // Send a 0-msat update_add_htlc to fail the channel.
3334 let update_add_htlc = msgs::UpdateAddHTLC {
3340 onion_routing_packet,
3342 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3344 let events = nodes[0].node.get_and_clear_pending_events();
3345 assert_eq!(events.len(), 2);
3346 // Check that Alice fails backward the pending HTLC from the second payment.
3348 Event::PaymentPathFailed { payment_hash, .. } => {
3349 assert_eq!(payment_hash, failed_payment_hash);
3351 _ => panic!("Unexpected event"),
3354 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3355 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3357 _ => panic!("Unexpected event {:?}", events[1]),
3359 check_closed_broadcast!(nodes[0], true);
3360 check_added_monitors!(nodes[0], 1);
3364 fn test_htlc_ignore_latest_remote_commitment() {
3365 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3366 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3367 let chanmon_cfgs = create_chanmon_cfgs(2);
3368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3370 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3371 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3373 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3374 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3375 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3376 check_closed_broadcast!(nodes[0], true);
3377 check_added_monitors!(nodes[0], 1);
3378 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3380 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3381 assert_eq!(node_txn.len(), 3);
3382 assert_eq!(node_txn[0], node_txn[1]);
3384 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3385 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3386 check_closed_broadcast!(nodes[1], true);
3387 check_added_monitors!(nodes[1], 1);
3388 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3390 // Duplicate the connect_block call since this may happen due to other listeners
3391 // registering new transactions
3392 header.prev_blockhash = header.block_hash();
3393 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3397 fn test_force_close_fail_back() {
3398 // Check which HTLCs are failed-backwards on channel force-closure
3399 let chanmon_cfgs = create_chanmon_cfgs(3);
3400 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3401 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3402 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3403 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3404 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3406 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3408 let mut payment_event = {
3409 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3410 check_added_monitors!(nodes[0], 1);
3412 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3413 assert_eq!(events.len(), 1);
3414 SendEvent::from_event(events.remove(0))
3417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3418 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3420 expect_pending_htlcs_forwardable!(nodes[1]);
3422 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3423 assert_eq!(events_2.len(), 1);
3424 payment_event = SendEvent::from_event(events_2.remove(0));
3425 assert_eq!(payment_event.msgs.len(), 1);
3427 check_added_monitors!(nodes[1], 1);
3428 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3429 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3430 check_added_monitors!(nodes[2], 1);
3431 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3433 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3434 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3435 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3437 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3438 check_closed_broadcast!(nodes[2], true);
3439 check_added_monitors!(nodes[2], 1);
3440 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3442 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3443 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3444 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3445 // back to nodes[1] upon timeout otherwise.
3446 assert_eq!(node_txn.len(), 1);
3450 mine_transaction(&nodes[1], &tx);
3452 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3453 check_closed_broadcast!(nodes[1], true);
3454 check_added_monitors!(nodes[1], 1);
3455 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3457 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3459 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3460 .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);
3462 mine_transaction(&nodes[2], &tx);
3463 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3464 assert_eq!(node_txn.len(), 1);
3465 assert_eq!(node_txn[0].input.len(), 1);
3466 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3467 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3468 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3470 check_spends!(node_txn[0], tx);
3474 fn test_dup_events_on_peer_disconnect() {
3475 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3476 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3477 // as we used to generate the event immediately upon receipt of the payment preimage in the
3478 // update_fulfill_htlc message.
3480 let chanmon_cfgs = create_chanmon_cfgs(2);
3481 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3482 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3483 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3484 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3486 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3488 nodes[1].node.claim_funds(payment_preimage);
3489 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3490 check_added_monitors!(nodes[1], 1);
3491 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3492 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3493 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3495 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3496 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3498 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3499 expect_payment_path_successful!(nodes[0]);
3503 fn test_peer_disconnected_before_funding_broadcasted() {
3504 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3505 // before the funding transaction has been broadcasted.
3506 let chanmon_cfgs = create_chanmon_cfgs(2);
3507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3509 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3511 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3512 // broadcasted, even though it's created by `nodes[0]`.
3513 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();
3514 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3515 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3516 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3517 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3519 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3520 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3522 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3524 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3525 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3527 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3528 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3531 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3534 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3535 // disconnected before the funding transaction was broadcasted.
3536 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3537 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3539 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3540 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3544 fn test_simple_peer_disconnect() {
3545 // Test that we can reconnect when there are no lost messages
3546 let chanmon_cfgs = create_chanmon_cfgs(3);
3547 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3548 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3549 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3550 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3551 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3553 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3554 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3555 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3557 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3558 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3559 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3560 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3562 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3563 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3564 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3566 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3567 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3568 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3569 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
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);
3574 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3575 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3577 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3579 let events = nodes[0].node.get_and_clear_pending_events();
3580 assert_eq!(events.len(), 3);
3582 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3583 assert_eq!(payment_preimage, payment_preimage_3);
3584 assert_eq!(payment_hash, payment_hash_3);
3586 _ => panic!("Unexpected event"),
3589 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3590 assert_eq!(payment_hash, payment_hash_5);
3591 assert!(payment_failed_permanently);
3593 _ => panic!("Unexpected event"),
3596 Event::PaymentPathSuccessful { .. } => {},
3597 _ => panic!("Unexpected event"),
3601 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3602 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3605 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3606 // Test that we can reconnect when in-flight HTLC updates get dropped
3607 let chanmon_cfgs = create_chanmon_cfgs(2);
3608 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3609 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3610 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3612 let mut as_channel_ready = None;
3613 if messages_delivered == 0 {
3614 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3615 as_channel_ready = Some(channel_ready);
3616 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3617 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3618 // it before the channel_reestablish message.
3620 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3623 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3625 let payment_event = {
3626 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3627 check_added_monitors!(nodes[0], 1);
3629 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3630 assert_eq!(events.len(), 1);
3631 SendEvent::from_event(events.remove(0))
3633 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3635 if messages_delivered < 2 {
3636 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3638 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3639 if messages_delivered >= 3 {
3640 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3641 check_added_monitors!(nodes[1], 1);
3642 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3644 if messages_delivered >= 4 {
3645 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3646 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3647 check_added_monitors!(nodes[0], 1);
3649 if messages_delivered >= 5 {
3650 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3651 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3652 // No commitment_signed so get_event_msg's assert(len == 1) passes
3653 check_added_monitors!(nodes[0], 1);
3655 if messages_delivered >= 6 {
3656 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3657 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3658 check_added_monitors!(nodes[1], 1);
3665 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3666 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3667 if messages_delivered < 3 {
3668 if simulate_broken_lnd {
3669 // lnd has a long-standing bug where they send a channel_ready prior to a
3670 // channel_reestablish if you reconnect prior to channel_ready time.
3672 // Here we simulate that behavior, delivering a channel_ready immediately on
3673 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3674 // in `reconnect_nodes` but we currently don't fail based on that.
3676 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3677 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3679 // Even if the channel_ready messages get exchanged, as long as nothing further was
3680 // received on either side, both sides will need to resend them.
3681 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3682 } else if messages_delivered == 3 {
3683 // nodes[0] still wants its RAA + commitment_signed
3684 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3685 } else if messages_delivered == 4 {
3686 // nodes[0] still wants its commitment_signed
3687 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3688 } else if messages_delivered == 5 {
3689 // nodes[1] still wants its final RAA
3690 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3691 } else if messages_delivered == 6 {
3692 // Everything was delivered...
3693 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3696 let events_1 = nodes[1].node.get_and_clear_pending_events();
3697 if messages_delivered == 0 {
3698 assert_eq!(events_1.len(), 2);
3700 Event::ChannelReady { .. } => { },
3701 _ => panic!("Unexpected event"),
3704 Event::PendingHTLCsForwardable { .. } => { },
3705 _ => panic!("Unexpected event"),
3708 assert_eq!(events_1.len(), 1);
3710 Event::PendingHTLCsForwardable { .. } => { },
3711 _ => panic!("Unexpected event"),
3715 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3716 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3717 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3719 nodes[1].node.process_pending_htlc_forwards();
3721 let events_2 = nodes[1].node.get_and_clear_pending_events();
3722 assert_eq!(events_2.len(), 1);
3724 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3725 assert_eq!(payment_hash_1, *payment_hash);
3726 assert_eq!(amount_msat, 1_000_000);
3728 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3729 assert!(payment_preimage.is_none());
3730 assert_eq!(payment_secret_1, *payment_secret);
3732 _ => panic!("expected PaymentPurpose::InvoicePayment")
3735 _ => panic!("Unexpected event"),
3738 nodes[1].node.claim_funds(payment_preimage_1);
3739 check_added_monitors!(nodes[1], 1);
3740 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3742 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3743 assert_eq!(events_3.len(), 1);
3744 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3745 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3746 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3747 assert!(updates.update_add_htlcs.is_empty());
3748 assert!(updates.update_fail_htlcs.is_empty());
3749 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3750 assert!(updates.update_fail_malformed_htlcs.is_empty());
3751 assert!(updates.update_fee.is_none());
3752 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3754 _ => panic!("Unexpected event"),
3757 if messages_delivered >= 1 {
3758 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3760 let events_4 = nodes[0].node.get_and_clear_pending_events();
3761 assert_eq!(events_4.len(), 1);
3763 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3764 assert_eq!(payment_preimage_1, *payment_preimage);
3765 assert_eq!(payment_hash_1, *payment_hash);
3767 _ => panic!("Unexpected event"),
3770 if messages_delivered >= 2 {
3771 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3772 check_added_monitors!(nodes[0], 1);
3773 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3775 if messages_delivered >= 3 {
3776 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3777 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3778 check_added_monitors!(nodes[1], 1);
3780 if messages_delivered >= 4 {
3781 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3782 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3783 // No commitment_signed so get_event_msg's assert(len == 1) passes
3784 check_added_monitors!(nodes[1], 1);
3786 if messages_delivered >= 5 {
3787 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3788 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3789 check_added_monitors!(nodes[0], 1);
3796 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3797 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3798 if messages_delivered < 2 {
3799 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3800 if messages_delivered < 1 {
3801 expect_payment_sent!(nodes[0], payment_preimage_1);
3803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3805 } else if messages_delivered == 2 {
3806 // nodes[0] still wants its RAA + commitment_signed
3807 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3808 } else if messages_delivered == 3 {
3809 // nodes[0] still wants its commitment_signed
3810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3811 } else if messages_delivered == 4 {
3812 // nodes[1] still wants its final RAA
3813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3814 } else if messages_delivered == 5 {
3815 // Everything was delivered...
3816 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3819 if messages_delivered == 1 || messages_delivered == 2 {
3820 expect_payment_path_successful!(nodes[0]);
3823 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3824 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3825 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3827 if messages_delivered > 2 {
3828 expect_payment_path_successful!(nodes[0]);
3831 // Channel should still work fine...
3832 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3833 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3834 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3838 fn test_drop_messages_peer_disconnect_a() {
3839 do_test_drop_messages_peer_disconnect(0, true);
3840 do_test_drop_messages_peer_disconnect(0, false);
3841 do_test_drop_messages_peer_disconnect(1, false);
3842 do_test_drop_messages_peer_disconnect(2, false);
3846 fn test_drop_messages_peer_disconnect_b() {
3847 do_test_drop_messages_peer_disconnect(3, false);
3848 do_test_drop_messages_peer_disconnect(4, false);
3849 do_test_drop_messages_peer_disconnect(5, false);
3850 do_test_drop_messages_peer_disconnect(6, false);
3854 fn test_funding_peer_disconnect() {
3855 // Test that we can lock in our funding tx while disconnected
3856 let chanmon_cfgs = create_chanmon_cfgs(2);
3857 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3858 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3859 let persister: test_utils::TestPersister;
3860 let new_chain_monitor: test_utils::TestChainMonitor;
3861 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3862 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3863 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3865 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3866 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3868 confirm_transaction(&nodes[0], &tx);
3869 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3870 assert!(events_1.is_empty());
3872 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3874 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3875 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3877 confirm_transaction(&nodes[1], &tx);
3878 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3879 assert!(events_2.is_empty());
3881 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3882 let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
3883 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3884 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
3886 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3887 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3888 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3889 assert_eq!(events_3.len(), 1);
3890 let as_channel_ready = match events_3[0] {
3891 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3892 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3895 _ => panic!("Unexpected event {:?}", events_3[0]),
3898 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3899 // announcement_signatures as well as channel_update.
3900 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3901 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3902 assert_eq!(events_4.len(), 3);
3904 let bs_channel_ready = match events_4[0] {
3905 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3906 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3907 chan_id = msg.channel_id;
3910 _ => panic!("Unexpected event {:?}", events_4[0]),
3912 let bs_announcement_sigs = match events_4[1] {
3913 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3914 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3917 _ => panic!("Unexpected event {:?}", events_4[1]),
3920 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3921 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3923 _ => panic!("Unexpected event {:?}", events_4[2]),
3926 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3927 // generates a duplicative private channel_update
3928 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3929 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3930 assert_eq!(events_5.len(), 1);
3932 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3933 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3935 _ => panic!("Unexpected event {:?}", events_5[0]),
3938 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3939 // announcement_signatures.
3940 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3941 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3942 assert_eq!(events_6.len(), 1);
3943 let as_announcement_sigs = match events_6[0] {
3944 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3945 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3948 _ => panic!("Unexpected event {:?}", events_6[0]),
3950 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
3951 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
3953 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3954 // broadcast the channel announcement globally, as well as re-send its (now-public)
3956 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3957 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3958 assert_eq!(events_7.len(), 1);
3959 let (chan_announcement, as_update) = match events_7[0] {
3960 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3961 (msg.clone(), update_msg.clone())
3963 _ => panic!("Unexpected event {:?}", events_7[0]),
3966 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3967 // same channel_announcement.
3968 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3969 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3970 assert_eq!(events_8.len(), 1);
3971 let bs_update = match events_8[0] {
3972 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3973 assert_eq!(*msg, chan_announcement);
3976 _ => panic!("Unexpected event {:?}", events_8[0]),
3979 // Provide the channel announcement and public updates to the network graph
3980 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3981 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3982 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3984 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3985 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3986 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3988 // Check that after deserialization and reconnection we can still generate an identical
3989 // channel_announcement from the cached signatures.
3990 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3992 let nodes_0_serialized = nodes[0].node.encode();
3993 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3994 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3996 persister = test_utils::TestPersister::new();
3997 let keys_manager = &chanmon_cfgs[0].keys_manager;
3998 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);
3999 nodes[0].chain_monitor = &new_chain_monitor;
4000 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4001 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4002 &mut chan_0_monitor_read, keys_manager).unwrap();
4003 assert!(chan_0_monitor_read.is_empty());
4005 let mut nodes_0_read = &nodes_0_serialized[..];
4006 let (_, nodes_0_deserialized_tmp) = {
4007 let mut channel_monitors = HashMap::new();
4008 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4009 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4010 default_config: UserConfig::default(),
4012 fee_estimator: node_cfgs[0].fee_estimator,
4013 chain_monitor: nodes[0].chain_monitor,
4014 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4015 logger: nodes[0].logger,
4019 nodes_0_deserialized = nodes_0_deserialized_tmp;
4020 assert!(nodes_0_read.is_empty());
4022 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4023 ChannelMonitorUpdateStatus::Completed);
4024 nodes[0].node = &nodes_0_deserialized;
4025 check_added_monitors!(nodes[0], 1);
4027 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4031 fn test_channel_ready_without_best_block_updated() {
4032 // Previously, if we were offline when a funding transaction was locked in, and then we came
4033 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4034 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4035 // channel_ready immediately instead.
4036 let chanmon_cfgs = create_chanmon_cfgs(2);
4037 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4038 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4039 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4040 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4042 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());
4044 let conf_height = nodes[0].best_block_info().1 + 1;
4045 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4046 let block_txn = [funding_tx];
4047 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4048 let conf_block_header = nodes[0].get_block_header(conf_height);
4049 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4051 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4052 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4053 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4057 fn test_drop_messages_peer_disconnect_dual_htlc() {
4058 // Test that we can handle reconnecting when both sides of a channel have pending
4059 // commitment_updates when we disconnect.
4060 let chanmon_cfgs = create_chanmon_cfgs(2);
4061 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4062 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4063 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4064 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4066 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4068 // Now try to send a second payment which will fail to send
4069 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4070 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4071 check_added_monitors!(nodes[0], 1);
4073 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4074 assert_eq!(events_1.len(), 1);
4076 MessageSendEvent::UpdateHTLCs { .. } => {},
4077 _ => panic!("Unexpected event"),
4080 nodes[1].node.claim_funds(payment_preimage_1);
4081 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4082 check_added_monitors!(nodes[1], 1);
4084 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4085 assert_eq!(events_2.len(), 1);
4087 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 } } => {
4088 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4089 assert!(update_add_htlcs.is_empty());
4090 assert_eq!(update_fulfill_htlcs.len(), 1);
4091 assert!(update_fail_htlcs.is_empty());
4092 assert!(update_fail_malformed_htlcs.is_empty());
4093 assert!(update_fee.is_none());
4095 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4096 let events_3 = nodes[0].node.get_and_clear_pending_events();
4097 assert_eq!(events_3.len(), 1);
4099 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4100 assert_eq!(*payment_preimage, payment_preimage_1);
4101 assert_eq!(*payment_hash, payment_hash_1);
4103 _ => panic!("Unexpected event"),
4106 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4107 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4108 // No commitment_signed so get_event_msg's assert(len == 1) passes
4109 check_added_monitors!(nodes[0], 1);
4111 _ => panic!("Unexpected event"),
4114 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4115 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4117 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4118 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4119 assert_eq!(reestablish_1.len(), 1);
4120 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4121 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4122 assert_eq!(reestablish_2.len(), 1);
4124 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4125 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4126 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4127 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4129 assert!(as_resp.0.is_none());
4130 assert!(bs_resp.0.is_none());
4132 assert!(bs_resp.1.is_none());
4133 assert!(bs_resp.2.is_none());
4135 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4137 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4138 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4139 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4140 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4141 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4142 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4143 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4144 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4145 // No commitment_signed so get_event_msg's assert(len == 1) passes
4146 check_added_monitors!(nodes[1], 1);
4148 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4149 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4150 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4151 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4152 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4153 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4154 assert!(bs_second_commitment_signed.update_fee.is_none());
4155 check_added_monitors!(nodes[1], 1);
4157 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4158 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4159 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4160 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4161 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4162 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4163 assert!(as_commitment_signed.update_fee.is_none());
4164 check_added_monitors!(nodes[0], 1);
4166 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4167 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4168 // No commitment_signed so get_event_msg's assert(len == 1) passes
4169 check_added_monitors!(nodes[0], 1);
4171 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4172 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4173 // No commitment_signed so get_event_msg's assert(len == 1) passes
4174 check_added_monitors!(nodes[1], 1);
4176 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4177 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4178 check_added_monitors!(nodes[1], 1);
4180 expect_pending_htlcs_forwardable!(nodes[1]);
4182 let events_5 = nodes[1].node.get_and_clear_pending_events();
4183 assert_eq!(events_5.len(), 1);
4185 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4186 assert_eq!(payment_hash_2, *payment_hash);
4188 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4189 assert!(payment_preimage.is_none());
4190 assert_eq!(payment_secret_2, *payment_secret);
4192 _ => panic!("expected PaymentPurpose::InvoicePayment")
4195 _ => panic!("Unexpected event"),
4198 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4199 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4200 check_added_monitors!(nodes[0], 1);
4202 expect_payment_path_successful!(nodes[0]);
4203 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4206 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4207 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4208 // to avoid our counterparty failing the channel.
4209 let chanmon_cfgs = create_chanmon_cfgs(2);
4210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4212 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4214 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4216 let our_payment_hash = if send_partial_mpp {
4217 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4218 // Use the utility function send_payment_along_path to send the payment with MPP data which
4219 // indicates there are more HTLCs coming.
4220 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.
4221 let payment_id = PaymentId([42; 32]);
4222 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();
4223 check_added_monitors!(nodes[0], 1);
4224 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4225 assert_eq!(events.len(), 1);
4226 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4227 // hop should *not* yet generate any PaymentReceived event(s).
4228 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4231 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4234 let mut block = Block {
4235 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4238 connect_block(&nodes[0], &block);
4239 connect_block(&nodes[1], &block);
4240 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4241 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4242 block.header.prev_blockhash = block.block_hash();
4243 connect_block(&nodes[0], &block);
4244 connect_block(&nodes[1], &block);
4247 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4249 check_added_monitors!(nodes[1], 1);
4250 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4251 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4252 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4253 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4254 assert!(htlc_timeout_updates.update_fee.is_none());
4256 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4257 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4258 // 100_000 msat as u64, followed by the height at which we failed back above
4259 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4260 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4261 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4265 fn test_htlc_timeout() {
4266 do_test_htlc_timeout(true);
4267 do_test_htlc_timeout(false);
4270 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4271 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4272 let chanmon_cfgs = create_chanmon_cfgs(3);
4273 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4274 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4275 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4276 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4277 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4279 // Make sure all nodes are at the same starting height
4280 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4281 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4282 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4284 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4285 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4287 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4289 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4290 check_added_monitors!(nodes[1], 1);
4292 // Now attempt to route a second payment, which should be placed in the holding cell
4293 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4294 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4295 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4297 check_added_monitors!(nodes[0], 1);
4298 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4299 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4300 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4301 expect_pending_htlcs_forwardable!(nodes[1]);
4303 check_added_monitors!(nodes[1], 0);
4305 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4306 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4307 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4308 connect_blocks(&nodes[1], 1);
4311 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 }]);
4312 check_added_monitors!(nodes[1], 1);
4313 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4314 assert_eq!(fail_commit.len(), 1);
4315 match fail_commit[0] {
4316 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4317 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4318 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4320 _ => unreachable!(),
4322 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4324 let events = nodes[1].node.get_and_clear_pending_events();
4325 assert_eq!(events.len(), 2);
4326 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4327 assert_eq!(*payment_hash, second_payment_hash);
4328 } else { panic!("Unexpected event"); }
4329 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4330 assert_eq!(*payment_hash, second_payment_hash);
4331 } else { panic!("Unexpected event"); }
4336 fn test_holding_cell_htlc_add_timeouts() {
4337 do_test_holding_cell_htlc_add_timeouts(false);
4338 do_test_holding_cell_htlc_add_timeouts(true);
4342 fn test_no_txn_manager_serialize_deserialize() {
4343 let chanmon_cfgs = create_chanmon_cfgs(2);
4344 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4345 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4346 let logger: test_utils::TestLogger;
4347 let fee_estimator: test_utils::TestFeeEstimator;
4348 let persister: test_utils::TestPersister;
4349 let new_chain_monitor: test_utils::TestChainMonitor;
4350 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4351 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4353 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4355 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4357 let nodes_0_serialized = nodes[0].node.encode();
4358 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4359 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4360 .write(&mut chan_0_monitor_serialized).unwrap();
4362 logger = test_utils::TestLogger::new();
4363 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4364 persister = test_utils::TestPersister::new();
4365 let keys_manager = &chanmon_cfgs[0].keys_manager;
4366 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4367 nodes[0].chain_monitor = &new_chain_monitor;
4368 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4369 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4370 &mut chan_0_monitor_read, keys_manager).unwrap();
4371 assert!(chan_0_monitor_read.is_empty());
4373 let mut nodes_0_read = &nodes_0_serialized[..];
4374 let config = UserConfig::default();
4375 let (_, nodes_0_deserialized_tmp) = {
4376 let mut channel_monitors = HashMap::new();
4377 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4378 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4379 default_config: config,
4381 fee_estimator: &fee_estimator,
4382 chain_monitor: nodes[0].chain_monitor,
4383 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4388 nodes_0_deserialized = nodes_0_deserialized_tmp;
4389 assert!(nodes_0_read.is_empty());
4391 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4392 ChannelMonitorUpdateStatus::Completed);
4393 nodes[0].node = &nodes_0_deserialized;
4394 assert_eq!(nodes[0].node.list_channels().len(), 1);
4395 check_added_monitors!(nodes[0], 1);
4397 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4398 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4399 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4400 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4402 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4403 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4404 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4405 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4407 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4408 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4409 for node in nodes.iter() {
4410 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4411 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4412 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4415 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4419 fn test_manager_serialize_deserialize_events() {
4420 // This test makes sure the events field in ChannelManager survives de/serialization
4421 let chanmon_cfgs = create_chanmon_cfgs(2);
4422 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4423 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4424 let fee_estimator: test_utils::TestFeeEstimator;
4425 let persister: test_utils::TestPersister;
4426 let logger: test_utils::TestLogger;
4427 let new_chain_monitor: test_utils::TestChainMonitor;
4428 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4431 // Start creating a channel, but stop right before broadcasting the funding transaction
4432 let channel_value = 100000;
4433 let push_msat = 10001;
4434 let a_flags = channelmanager::provided_init_features();
4435 let b_flags = channelmanager::provided_init_features();
4436 let node_a = nodes.remove(0);
4437 let node_b = nodes.remove(0);
4438 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4439 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()));
4440 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()));
4442 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4444 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4445 check_added_monitors!(node_a, 0);
4447 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()));
4449 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4450 assert_eq!(added_monitors.len(), 1);
4451 assert_eq!(added_monitors[0].0, funding_output);
4452 added_monitors.clear();
4455 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4456 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4458 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4459 assert_eq!(added_monitors.len(), 1);
4460 assert_eq!(added_monitors[0].0, funding_output);
4461 added_monitors.clear();
4463 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4468 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4469 let nodes_0_serialized = nodes[0].node.encode();
4470 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4471 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4473 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4474 logger = test_utils::TestLogger::new();
4475 persister = test_utils::TestPersister::new();
4476 let keys_manager = &chanmon_cfgs[0].keys_manager;
4477 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4478 nodes[0].chain_monitor = &new_chain_monitor;
4479 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4480 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4481 &mut chan_0_monitor_read, keys_manager).unwrap();
4482 assert!(chan_0_monitor_read.is_empty());
4484 let mut nodes_0_read = &nodes_0_serialized[..];
4485 let config = UserConfig::default();
4486 let (_, nodes_0_deserialized_tmp) = {
4487 let mut channel_monitors = HashMap::new();
4488 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4489 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4490 default_config: config,
4492 fee_estimator: &fee_estimator,
4493 chain_monitor: nodes[0].chain_monitor,
4494 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4499 nodes_0_deserialized = nodes_0_deserialized_tmp;
4500 assert!(nodes_0_read.is_empty());
4502 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4504 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4505 ChannelMonitorUpdateStatus::Completed);
4506 nodes[0].node = &nodes_0_deserialized;
4508 // After deserializing, make sure the funding_transaction is still held by the channel manager
4509 let events_4 = nodes[0].node.get_and_clear_pending_events();
4510 assert_eq!(events_4.len(), 0);
4511 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4512 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4514 // Make sure the channel is functioning as though the de/serialization never happened
4515 assert_eq!(nodes[0].node.list_channels().len(), 1);
4516 check_added_monitors!(nodes[0], 1);
4518 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4519 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4520 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4521 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4523 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4524 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4525 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4526 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4528 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4529 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4530 for node in nodes.iter() {
4531 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4532 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4533 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4536 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4540 fn test_simple_manager_serialize_deserialize() {
4541 let chanmon_cfgs = create_chanmon_cfgs(2);
4542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4544 let logger: test_utils::TestLogger;
4545 let fee_estimator: test_utils::TestFeeEstimator;
4546 let persister: test_utils::TestPersister;
4547 let new_chain_monitor: test_utils::TestChainMonitor;
4548 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4549 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4550 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4552 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4553 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4555 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4557 let nodes_0_serialized = nodes[0].node.encode();
4558 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4559 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4561 logger = test_utils::TestLogger::new();
4562 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4563 persister = test_utils::TestPersister::new();
4564 let keys_manager = &chanmon_cfgs[0].keys_manager;
4565 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4566 nodes[0].chain_monitor = &new_chain_monitor;
4567 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4568 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4569 &mut chan_0_monitor_read, keys_manager).unwrap();
4570 assert!(chan_0_monitor_read.is_empty());
4572 let mut nodes_0_read = &nodes_0_serialized[..];
4573 let (_, nodes_0_deserialized_tmp) = {
4574 let mut channel_monitors = HashMap::new();
4575 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4576 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4577 default_config: UserConfig::default(),
4579 fee_estimator: &fee_estimator,
4580 chain_monitor: nodes[0].chain_monitor,
4581 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4586 nodes_0_deserialized = nodes_0_deserialized_tmp;
4587 assert!(nodes_0_read.is_empty());
4589 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4590 ChannelMonitorUpdateStatus::Completed);
4591 nodes[0].node = &nodes_0_deserialized;
4592 check_added_monitors!(nodes[0], 1);
4594 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4596 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4597 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4601 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4602 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4603 let chanmon_cfgs = create_chanmon_cfgs(4);
4604 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4605 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4606 let logger: test_utils::TestLogger;
4607 let fee_estimator: test_utils::TestFeeEstimator;
4608 let persister: test_utils::TestPersister;
4609 let new_chain_monitor: test_utils::TestChainMonitor;
4610 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4611 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4612 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4613 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4614 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4616 let mut node_0_stale_monitors_serialized = Vec::new();
4617 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4618 let mut writer = test_utils::TestVecWriter(Vec::new());
4619 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4620 node_0_stale_monitors_serialized.push(writer.0);
4623 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4625 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4626 let nodes_0_serialized = nodes[0].node.encode();
4628 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4629 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4630 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4631 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4633 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4635 let mut node_0_monitors_serialized = Vec::new();
4636 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4637 let mut writer = test_utils::TestVecWriter(Vec::new());
4638 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4639 node_0_monitors_serialized.push(writer.0);
4642 logger = test_utils::TestLogger::new();
4643 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4644 persister = test_utils::TestPersister::new();
4645 let keys_manager = &chanmon_cfgs[0].keys_manager;
4646 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4647 nodes[0].chain_monitor = &new_chain_monitor;
4650 let mut node_0_stale_monitors = Vec::new();
4651 for serialized in node_0_stale_monitors_serialized.iter() {
4652 let mut read = &serialized[..];
4653 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4654 assert!(read.is_empty());
4655 node_0_stale_monitors.push(monitor);
4658 let mut node_0_monitors = Vec::new();
4659 for serialized in node_0_monitors_serialized.iter() {
4660 let mut read = &serialized[..];
4661 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4662 assert!(read.is_empty());
4663 node_0_monitors.push(monitor);
4666 let mut nodes_0_read = &nodes_0_serialized[..];
4667 if let Err(msgs::DecodeError::InvalidValue) =
4668 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4669 default_config: UserConfig::default(),
4671 fee_estimator: &fee_estimator,
4672 chain_monitor: nodes[0].chain_monitor,
4673 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4675 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4677 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4680 let mut nodes_0_read = &nodes_0_serialized[..];
4681 let (_, nodes_0_deserialized_tmp) =
4682 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4683 default_config: UserConfig::default(),
4685 fee_estimator: &fee_estimator,
4686 chain_monitor: nodes[0].chain_monitor,
4687 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4689 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4691 nodes_0_deserialized = nodes_0_deserialized_tmp;
4692 assert!(nodes_0_read.is_empty());
4694 { // Channel close should result in a commitment tx
4695 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4696 assert_eq!(txn.len(), 1);
4697 check_spends!(txn[0], funding_tx);
4698 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4701 for monitor in node_0_monitors.drain(..) {
4702 assert_eq!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
4703 ChannelMonitorUpdateStatus::Completed);
4704 check_added_monitors!(nodes[0], 1);
4706 nodes[0].node = &nodes_0_deserialized;
4707 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4709 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4710 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4711 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4712 //... and we can even still claim the payment!
4713 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4715 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4716 let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
4717 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4718 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4719 let mut found_err = false;
4720 for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
4721 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
4723 &ErrorAction::SendErrorMessage { ref msg } => {
4724 assert_eq!(msg.channel_id, channel_id);
4725 assert!(!found_err);
4728 _ => panic!("Unexpected event!"),
4735 macro_rules! check_spendable_outputs {
4736 ($node: expr, $keysinterface: expr) => {
4738 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4739 let mut txn = Vec::new();
4740 let mut all_outputs = Vec::new();
4741 let secp_ctx = Secp256k1::new();
4742 for event in events.drain(..) {
4744 Event::SpendableOutputs { mut outputs } => {
4745 for outp in outputs.drain(..) {
4746 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4747 all_outputs.push(outp);
4750 _ => panic!("Unexpected event"),
4753 if all_outputs.len() > 1 {
4754 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) {
4764 fn test_claim_sizeable_push_msat() {
4765 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4766 let chanmon_cfgs = create_chanmon_cfgs(2);
4767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4769 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4771 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());
4772 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4773 check_closed_broadcast!(nodes[1], true);
4774 check_added_monitors!(nodes[1], 1);
4775 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4776 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4777 assert_eq!(node_txn.len(), 1);
4778 check_spends!(node_txn[0], chan.3);
4779 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
4781 mine_transaction(&nodes[1], &node_txn[0]);
4782 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4784 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4785 assert_eq!(spend_txn.len(), 1);
4786 assert_eq!(spend_txn[0].input.len(), 1);
4787 check_spends!(spend_txn[0], node_txn[0]);
4788 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4792 fn test_claim_on_remote_sizeable_push_msat() {
4793 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4794 // to_remote output is encumbered by a P2WPKH
4795 let chanmon_cfgs = create_chanmon_cfgs(2);
4796 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4797 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4798 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4800 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());
4801 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4802 check_closed_broadcast!(nodes[0], true);
4803 check_added_monitors!(nodes[0], 1);
4804 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4806 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4807 assert_eq!(node_txn.len(), 1);
4808 check_spends!(node_txn[0], chan.3);
4809 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
4811 mine_transaction(&nodes[1], &node_txn[0]);
4812 check_closed_broadcast!(nodes[1], true);
4813 check_added_monitors!(nodes[1], 1);
4814 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4815 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4817 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4818 assert_eq!(spend_txn.len(), 1);
4819 check_spends!(spend_txn[0], node_txn[0]);
4823 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4824 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4825 // to_remote output is encumbered by a P2WPKH
4827 let chanmon_cfgs = create_chanmon_cfgs(2);
4828 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4829 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4830 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4832 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4833 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4834 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4835 assert_eq!(revoked_local_txn[0].input.len(), 1);
4836 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4838 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4839 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4840 check_closed_broadcast!(nodes[1], true);
4841 check_added_monitors!(nodes[1], 1);
4842 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4844 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4845 mine_transaction(&nodes[1], &node_txn[0]);
4846 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4848 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4849 assert_eq!(spend_txn.len(), 3);
4850 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4851 check_spends!(spend_txn[1], node_txn[0]);
4852 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4856 fn test_static_spendable_outputs_preimage_tx() {
4857 let chanmon_cfgs = create_chanmon_cfgs(2);
4858 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4859 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4860 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4862 // Create some initial channels
4863 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4865 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4867 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4868 assert_eq!(commitment_tx[0].input.len(), 1);
4869 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4871 // Settle A's commitment tx on B's chain
4872 nodes[1].node.claim_funds(payment_preimage);
4873 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4874 check_added_monitors!(nodes[1], 1);
4875 mine_transaction(&nodes[1], &commitment_tx[0]);
4876 check_added_monitors!(nodes[1], 1);
4877 let events = nodes[1].node.get_and_clear_pending_msg_events();
4879 MessageSendEvent::UpdateHTLCs { .. } => {},
4880 _ => panic!("Unexpected event"),
4883 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4884 _ => panic!("Unexepected event"),
4887 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4888 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4889 assert_eq!(node_txn.len(), 3);
4890 check_spends!(node_txn[0], commitment_tx[0]);
4891 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4892 check_spends!(node_txn[1], chan_1.3);
4893 check_spends!(node_txn[2], node_txn[1]);
4895 mine_transaction(&nodes[1], &node_txn[0]);
4896 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4897 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4899 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4900 assert_eq!(spend_txn.len(), 1);
4901 check_spends!(spend_txn[0], node_txn[0]);
4905 fn test_static_spendable_outputs_timeout_tx() {
4906 let chanmon_cfgs = create_chanmon_cfgs(2);
4907 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4908 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4909 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4911 // Create some initial channels
4912 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4914 // Rebalance the network a bit by relaying one payment through all the channels ...
4915 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4917 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4919 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4920 assert_eq!(commitment_tx[0].input.len(), 1);
4921 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4923 // Settle A's commitment tx on B' chain
4924 mine_transaction(&nodes[1], &commitment_tx[0]);
4925 check_added_monitors!(nodes[1], 1);
4926 let events = nodes[1].node.get_and_clear_pending_msg_events();
4928 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4929 _ => panic!("Unexpected event"),
4931 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4933 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4934 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4935 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4936 check_spends!(node_txn[0], chan_1.3.clone());
4937 check_spends!(node_txn[1], commitment_tx[0].clone());
4938 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4940 mine_transaction(&nodes[1], &node_txn[1]);
4941 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4942 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4943 expect_payment_failed!(nodes[1], our_payment_hash, false);
4945 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4946 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4947 check_spends!(spend_txn[0], commitment_tx[0]);
4948 check_spends!(spend_txn[1], node_txn[1]);
4949 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4953 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4954 let chanmon_cfgs = create_chanmon_cfgs(2);
4955 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4956 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4957 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4959 // Create some initial channels
4960 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4962 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4963 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4964 assert_eq!(revoked_local_txn[0].input.len(), 1);
4965 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4967 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4969 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4970 check_closed_broadcast!(nodes[1], true);
4971 check_added_monitors!(nodes[1], 1);
4972 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4974 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4975 assert_eq!(node_txn.len(), 2);
4976 assert_eq!(node_txn[0].input.len(), 2);
4977 check_spends!(node_txn[0], revoked_local_txn[0]);
4979 mine_transaction(&nodes[1], &node_txn[0]);
4980 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4982 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4983 assert_eq!(spend_txn.len(), 1);
4984 check_spends!(spend_txn[0], node_txn[0]);
4988 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4989 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4990 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4991 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4992 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4993 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4995 // Create some initial channels
4996 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4998 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4999 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5000 assert_eq!(revoked_local_txn[0].input.len(), 1);
5001 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5003 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5005 // A will generate HTLC-Timeout from revoked commitment tx
5006 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5007 check_closed_broadcast!(nodes[0], true);
5008 check_added_monitors!(nodes[0], 1);
5009 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5010 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5012 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5013 assert_eq!(revoked_htlc_txn.len(), 2);
5014 check_spends!(revoked_htlc_txn[0], chan_1.3);
5015 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5016 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5017 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5018 assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
5020 // B will generate justice tx from A's revoked commitment/HTLC tx
5021 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5022 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5023 check_closed_broadcast!(nodes[1], true);
5024 check_added_monitors!(nodes[1], 1);
5025 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5027 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5028 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5029 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5030 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5031 // transactions next...
5032 assert_eq!(node_txn[0].input.len(), 3);
5033 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5035 assert_eq!(node_txn[1].input.len(), 2);
5036 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5037 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5038 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5040 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5041 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5044 assert_eq!(node_txn[2].input.len(), 1);
5045 check_spends!(node_txn[2], chan_1.3);
5047 mine_transaction(&nodes[1], &node_txn[1]);
5048 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5050 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5051 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5052 assert_eq!(spend_txn.len(), 1);
5053 assert_eq!(spend_txn[0].input.len(), 1);
5054 check_spends!(spend_txn[0], node_txn[1]);
5058 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5059 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5060 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5061 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5062 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5063 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5065 // Create some initial channels
5066 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5068 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5069 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5070 assert_eq!(revoked_local_txn[0].input.len(), 1);
5071 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5073 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5074 assert_eq!(revoked_local_txn[0].output.len(), 2);
5076 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5078 // B will generate HTLC-Success from revoked commitment tx
5079 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5080 check_closed_broadcast!(nodes[1], true);
5081 check_added_monitors!(nodes[1], 1);
5082 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5083 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5085 assert_eq!(revoked_htlc_txn.len(), 2);
5086 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5087 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5088 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5090 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5091 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5092 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5094 // A will generate justice tx from B's revoked commitment/HTLC tx
5095 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5096 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5097 check_closed_broadcast!(nodes[0], true);
5098 check_added_monitors!(nodes[0], 1);
5099 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5101 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5102 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5104 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5105 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5106 // transactions next...
5107 assert_eq!(node_txn[0].input.len(), 2);
5108 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5109 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5110 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5112 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5113 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5116 assert_eq!(node_txn[1].input.len(), 1);
5117 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5119 check_spends!(node_txn[2], chan_1.3);
5121 mine_transaction(&nodes[0], &node_txn[1]);
5122 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5124 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5125 // didn't try to generate any new transactions.
5127 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5128 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5129 assert_eq!(spend_txn.len(), 3);
5130 assert_eq!(spend_txn[0].input.len(), 1);
5131 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5132 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5133 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5134 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5138 fn test_onchain_to_onchain_claim() {
5139 // Test that in case of channel closure, we detect the state of output and claim HTLC
5140 // on downstream peer's remote commitment tx.
5141 // First, have C claim an HTLC against its own latest commitment transaction.
5142 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5144 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5147 let chanmon_cfgs = create_chanmon_cfgs(3);
5148 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5149 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5150 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5152 // Create some initial channels
5153 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5154 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5156 // Ensure all nodes are at the same height
5157 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5158 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5159 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5160 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5162 // Rebalance the network a bit by relaying one payment through all the channels ...
5163 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5164 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5166 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5167 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5168 check_spends!(commitment_tx[0], chan_2.3);
5169 nodes[2].node.claim_funds(payment_preimage);
5170 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5171 check_added_monitors!(nodes[2], 1);
5172 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5173 assert!(updates.update_add_htlcs.is_empty());
5174 assert!(updates.update_fail_htlcs.is_empty());
5175 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5176 assert!(updates.update_fail_malformed_htlcs.is_empty());
5178 mine_transaction(&nodes[2], &commitment_tx[0]);
5179 check_closed_broadcast!(nodes[2], true);
5180 check_added_monitors!(nodes[2], 1);
5181 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5183 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5184 assert_eq!(c_txn.len(), 3);
5185 assert_eq!(c_txn[0], c_txn[2]);
5186 assert_eq!(commitment_tx[0], c_txn[1]);
5187 check_spends!(c_txn[1], chan_2.3);
5188 check_spends!(c_txn[2], c_txn[1]);
5189 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5190 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5191 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5192 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5194 // 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
5195 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5196 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5197 check_added_monitors!(nodes[1], 1);
5198 let events = nodes[1].node.get_and_clear_pending_events();
5199 assert_eq!(events.len(), 2);
5201 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5202 _ => panic!("Unexpected event"),
5205 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5206 assert_eq!(fee_earned_msat, Some(1000));
5207 assert_eq!(prev_channel_id, Some(chan_1.2));
5208 assert_eq!(claim_from_onchain_tx, true);
5209 assert_eq!(next_channel_id, Some(chan_2.2));
5211 _ => panic!("Unexpected event"),
5214 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5215 // ChannelMonitor: claim tx
5216 assert_eq!(b_txn.len(), 1);
5217 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5220 check_added_monitors!(nodes[1], 1);
5221 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5222 assert_eq!(msg_events.len(), 3);
5223 match msg_events[0] {
5224 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5225 _ => panic!("Unexpected event"),
5227 match msg_events[1] {
5228 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5229 _ => panic!("Unexpected event"),
5231 match msg_events[2] {
5232 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, .. } } => {
5233 assert!(update_add_htlcs.is_empty());
5234 assert!(update_fail_htlcs.is_empty());
5235 assert_eq!(update_fulfill_htlcs.len(), 1);
5236 assert!(update_fail_malformed_htlcs.is_empty());
5237 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5239 _ => panic!("Unexpected event"),
5241 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5242 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5243 mine_transaction(&nodes[1], &commitment_tx[0]);
5244 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5245 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5246 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5247 assert_eq!(b_txn.len(), 3);
5248 check_spends!(b_txn[1], chan_1.3);
5249 check_spends!(b_txn[2], b_txn[1]);
5250 check_spends!(b_txn[0], commitment_tx[0]);
5251 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5252 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5253 assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5255 check_closed_broadcast!(nodes[1], true);
5256 check_added_monitors!(nodes[1], 1);
5260 fn test_duplicate_payment_hash_one_failure_one_success() {
5261 // Topology : A --> B --> C --> D
5262 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5263 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5264 // we forward one of the payments onwards to D.
5265 let chanmon_cfgs = create_chanmon_cfgs(4);
5266 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5267 // When this test was written, the default base fee floated based on the HTLC count.
5268 // It is now fixed, so we simply set the fee to the expected value here.
5269 let mut config = test_default_channel_config();
5270 config.channel_config.forwarding_fee_base_msat = 196;
5271 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5272 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5273 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5275 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5276 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5277 create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5279 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5280 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5281 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5282 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5283 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5285 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5287 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5288 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5289 // script push size limit so that the below script length checks match
5290 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5291 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5292 .with_features(channelmanager::provided_invoice_features());
5293 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5294 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5296 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5297 assert_eq!(commitment_txn[0].input.len(), 1);
5298 check_spends!(commitment_txn[0], chan_2.3);
5300 mine_transaction(&nodes[1], &commitment_txn[0]);
5301 check_closed_broadcast!(nodes[1], true);
5302 check_added_monitors!(nodes[1], 1);
5303 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5304 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5306 let htlc_timeout_tx;
5307 { // Extract one of the two HTLC-Timeout transaction
5308 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5309 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5310 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5311 check_spends!(node_txn[0], chan_2.3);
5313 check_spends!(node_txn[1], commitment_txn[0]);
5314 assert_eq!(node_txn[1].input.len(), 1);
5316 if node_txn.len() > 3 {
5317 check_spends!(node_txn[2], commitment_txn[0]);
5318 assert_eq!(node_txn[2].input.len(), 1);
5319 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5321 check_spends!(node_txn[3], commitment_txn[0]);
5322 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5324 check_spends!(node_txn[2], commitment_txn[0]);
5325 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5328 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5329 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5330 if node_txn.len() > 3 {
5331 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5333 htlc_timeout_tx = node_txn[1].clone();
5336 nodes[2].node.claim_funds(our_payment_preimage);
5337 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5339 mine_transaction(&nodes[2], &commitment_txn[0]);
5340 check_added_monitors!(nodes[2], 2);
5341 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5342 let events = nodes[2].node.get_and_clear_pending_msg_events();
5344 MessageSendEvent::UpdateHTLCs { .. } => {},
5345 _ => panic!("Unexpected event"),
5348 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5349 _ => panic!("Unexepected event"),
5351 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5352 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)
5353 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5354 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5355 assert_eq!(htlc_success_txn[0].input.len(), 1);
5356 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5357 assert_eq!(htlc_success_txn[1].input.len(), 1);
5358 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5359 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5360 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5361 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5362 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5363 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5365 mine_transaction(&nodes[1], &htlc_timeout_tx);
5366 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5367 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 }]);
5368 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5369 assert!(htlc_updates.update_add_htlcs.is_empty());
5370 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5371 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5372 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5373 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5374 check_added_monitors!(nodes[1], 1);
5376 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5377 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5379 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5381 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5383 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5384 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5385 // and nodes[2] fee) is rounded down and then claimed in full.
5386 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5387 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5388 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5389 assert!(updates.update_add_htlcs.is_empty());
5390 assert!(updates.update_fail_htlcs.is_empty());
5391 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5392 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5393 assert!(updates.update_fail_malformed_htlcs.is_empty());
5394 check_added_monitors!(nodes[1], 1);
5396 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5397 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5399 let events = nodes[0].node.get_and_clear_pending_events();
5401 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5402 assert_eq!(*payment_preimage, our_payment_preimage);
5403 assert_eq!(*payment_hash, duplicate_payment_hash);
5405 _ => panic!("Unexpected event"),
5410 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5411 let chanmon_cfgs = create_chanmon_cfgs(2);
5412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5414 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5416 // Create some initial channels
5417 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5419 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5420 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5421 assert_eq!(local_txn.len(), 1);
5422 assert_eq!(local_txn[0].input.len(), 1);
5423 check_spends!(local_txn[0], chan_1.3);
5425 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5426 nodes[1].node.claim_funds(payment_preimage);
5427 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5428 check_added_monitors!(nodes[1], 1);
5430 mine_transaction(&nodes[1], &local_txn[0]);
5431 check_added_monitors!(nodes[1], 1);
5432 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5433 let events = nodes[1].node.get_and_clear_pending_msg_events();
5435 MessageSendEvent::UpdateHTLCs { .. } => {},
5436 _ => panic!("Unexpected event"),
5439 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5440 _ => panic!("Unexepected event"),
5443 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5444 assert_eq!(node_txn.len(), 3);
5445 assert_eq!(node_txn[0], node_txn[2]);
5446 assert_eq!(node_txn[1], local_txn[0]);
5447 assert_eq!(node_txn[0].input.len(), 1);
5448 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5449 check_spends!(node_txn[0], local_txn[0]);
5453 mine_transaction(&nodes[1], &node_tx);
5454 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5456 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5457 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5458 assert_eq!(spend_txn.len(), 1);
5459 assert_eq!(spend_txn[0].input.len(), 1);
5460 check_spends!(spend_txn[0], node_tx);
5461 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5464 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5465 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5466 // unrevoked commitment transaction.
5467 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5468 // a remote RAA before they could be failed backwards (and combinations thereof).
5469 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5470 // use the same payment hashes.
5471 // Thus, we use a six-node network:
5476 // And test where C fails back to A/B when D announces its latest commitment transaction
5477 let chanmon_cfgs = create_chanmon_cfgs(6);
5478 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5479 // When this test was written, the default base fee floated based on the HTLC count.
5480 // It is now fixed, so we simply set the fee to the expected value here.
5481 let mut config = test_default_channel_config();
5482 config.channel_config.forwarding_fee_base_msat = 196;
5483 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5484 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5485 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5487 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5488 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5489 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5490 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5491 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5493 // Rebalance and check output sanity...
5494 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5495 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5496 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5498 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5500 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
5502 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
5503 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5505 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
5507 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
5509 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5511 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5512 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5514 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());
5516 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());
5519 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5521 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5522 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
5525 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
5527 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5528 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());
5530 // Double-check that six of the new HTLC were added
5531 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5532 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5533 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5534 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5536 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5537 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5538 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5539 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5540 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5541 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5542 check_added_monitors!(nodes[4], 0);
5544 let failed_destinations = vec![
5545 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5546 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5547 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5548 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5550 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5551 check_added_monitors!(nodes[4], 1);
5553 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5554 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5555 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5556 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5557 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5558 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5560 // Fail 3rd below-dust and 7th above-dust HTLCs
5561 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5562 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5563 check_added_monitors!(nodes[5], 0);
5565 let failed_destinations_2 = vec![
5566 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5567 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5569 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5570 check_added_monitors!(nodes[5], 1);
5572 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5573 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5574 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5575 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5577 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5579 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5580 let failed_destinations_3 = vec![
5581 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5582 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5583 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5584 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5585 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5586 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5588 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5589 check_added_monitors!(nodes[3], 1);
5590 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5591 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5592 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5593 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5594 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5595 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5596 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5597 if deliver_last_raa {
5598 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5600 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5603 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5604 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5605 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5606 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5608 // We now broadcast the latest commitment transaction, which *should* result in failures for
5609 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5610 // the non-broadcast above-dust HTLCs.
5612 // Alternatively, we may broadcast the previous commitment transaction, which should only
5613 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5614 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5616 if announce_latest {
5617 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5619 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5621 let events = nodes[2].node.get_and_clear_pending_events();
5622 let close_event = if deliver_last_raa {
5623 assert_eq!(events.len(), 2 + 6);
5624 events.last().clone().unwrap()
5626 assert_eq!(events.len(), 1);
5627 events.last().clone().unwrap()
5630 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5631 _ => panic!("Unexpected event"),
5634 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5635 check_closed_broadcast!(nodes[2], true);
5636 if deliver_last_raa {
5637 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5639 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();
5640 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5642 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5643 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5645 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5648 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5650 check_added_monitors!(nodes[2], 3);
5652 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5653 assert_eq!(cs_msgs.len(), 2);
5654 let mut a_done = false;
5655 for msg in cs_msgs {
5657 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5658 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5659 // should be failed-backwards here.
5660 let target = if *node_id == nodes[0].node.get_our_node_id() {
5661 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5662 for htlc in &updates.update_fail_htlcs {
5663 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 });
5665 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5670 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5671 for htlc in &updates.update_fail_htlcs {
5672 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5674 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5675 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5678 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5679 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5680 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5681 if announce_latest {
5682 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5683 if *node_id == nodes[0].node.get_our_node_id() {
5684 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5687 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5689 _ => panic!("Unexpected event"),
5693 let as_events = nodes[0].node.get_and_clear_pending_events();
5694 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5695 let mut as_failds = HashSet::new();
5696 let mut as_updates = 0;
5697 for event in as_events.iter() {
5698 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5699 assert!(as_failds.insert(*payment_hash));
5700 if *payment_hash != payment_hash_2 {
5701 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5703 assert!(!payment_failed_permanently);
5705 if network_update.is_some() {
5708 } else { panic!("Unexpected event"); }
5710 assert!(as_failds.contains(&payment_hash_1));
5711 assert!(as_failds.contains(&payment_hash_2));
5712 if announce_latest {
5713 assert!(as_failds.contains(&payment_hash_3));
5714 assert!(as_failds.contains(&payment_hash_5));
5716 assert!(as_failds.contains(&payment_hash_6));
5718 let bs_events = nodes[1].node.get_and_clear_pending_events();
5719 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5720 let mut bs_failds = HashSet::new();
5721 let mut bs_updates = 0;
5722 for event in bs_events.iter() {
5723 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5724 assert!(bs_failds.insert(*payment_hash));
5725 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5726 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5728 assert!(!payment_failed_permanently);
5730 if network_update.is_some() {
5733 } else { panic!("Unexpected event"); }
5735 assert!(bs_failds.contains(&payment_hash_1));
5736 assert!(bs_failds.contains(&payment_hash_2));
5737 if announce_latest {
5738 assert!(bs_failds.contains(&payment_hash_4));
5740 assert!(bs_failds.contains(&payment_hash_5));
5742 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5743 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5744 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5745 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5746 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5747 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5751 fn test_fail_backwards_latest_remote_announce_a() {
5752 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5756 fn test_fail_backwards_latest_remote_announce_b() {
5757 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5761 fn test_fail_backwards_previous_remote_announce() {
5762 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5763 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5764 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5768 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5769 let chanmon_cfgs = create_chanmon_cfgs(2);
5770 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5771 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5772 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5774 // Create some initial channels
5775 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5777 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5778 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5779 assert_eq!(local_txn[0].input.len(), 1);
5780 check_spends!(local_txn[0], chan_1.3);
5782 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5783 mine_transaction(&nodes[0], &local_txn[0]);
5784 check_closed_broadcast!(nodes[0], true);
5785 check_added_monitors!(nodes[0], 1);
5786 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5787 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5789 let htlc_timeout = {
5790 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5791 assert_eq!(node_txn.len(), 2);
5792 check_spends!(node_txn[0], chan_1.3);
5793 assert_eq!(node_txn[1].input.len(), 1);
5794 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5795 check_spends!(node_txn[1], local_txn[0]);
5799 mine_transaction(&nodes[0], &htlc_timeout);
5800 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5801 expect_payment_failed!(nodes[0], our_payment_hash, false);
5803 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5804 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5805 assert_eq!(spend_txn.len(), 3);
5806 check_spends!(spend_txn[0], local_txn[0]);
5807 assert_eq!(spend_txn[1].input.len(), 1);
5808 check_spends!(spend_txn[1], htlc_timeout);
5809 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5810 assert_eq!(spend_txn[2].input.len(), 2);
5811 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5812 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5813 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5817 fn test_key_derivation_params() {
5818 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5819 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5820 // let us re-derive the channel key set to then derive a delayed_payment_key.
5822 let chanmon_cfgs = create_chanmon_cfgs(3);
5824 // We manually create the node configuration to backup the seed.
5825 let seed = [42; 32];
5826 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5827 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);
5828 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5829 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() };
5830 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5831 node_cfgs.remove(0);
5832 node_cfgs.insert(0, node);
5834 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5835 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5837 // Create some initial channels
5838 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5840 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5841 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5842 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5844 // Ensure all nodes are at the same height
5845 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5846 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5847 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5848 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5850 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5851 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5852 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5853 assert_eq!(local_txn_1[0].input.len(), 1);
5854 check_spends!(local_txn_1[0], chan_1.3);
5856 // We check funding pubkey are unique
5857 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]));
5858 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]));
5859 if from_0_funding_key_0 == from_1_funding_key_0
5860 || from_0_funding_key_0 == from_1_funding_key_1
5861 || from_0_funding_key_1 == from_1_funding_key_0
5862 || from_0_funding_key_1 == from_1_funding_key_1 {
5863 panic!("Funding pubkeys aren't unique");
5866 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5867 mine_transaction(&nodes[0], &local_txn_1[0]);
5868 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5869 check_closed_broadcast!(nodes[0], true);
5870 check_added_monitors!(nodes[0], 1);
5871 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5873 let htlc_timeout = {
5874 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5875 assert_eq!(node_txn[1].input.len(), 1);
5876 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5877 check_spends!(node_txn[1], local_txn_1[0]);
5881 mine_transaction(&nodes[0], &htlc_timeout);
5882 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5883 expect_payment_failed!(nodes[0], our_payment_hash, false);
5885 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5886 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5887 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5888 assert_eq!(spend_txn.len(), 3);
5889 check_spends!(spend_txn[0], local_txn_1[0]);
5890 assert_eq!(spend_txn[1].input.len(), 1);
5891 check_spends!(spend_txn[1], htlc_timeout);
5892 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5893 assert_eq!(spend_txn[2].input.len(), 2);
5894 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5895 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5896 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5900 fn test_static_output_closing_tx() {
5901 let chanmon_cfgs = create_chanmon_cfgs(2);
5902 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5903 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5904 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5906 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5908 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5909 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5911 mine_transaction(&nodes[0], &closing_tx);
5912 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5913 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5915 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5916 assert_eq!(spend_txn.len(), 1);
5917 check_spends!(spend_txn[0], closing_tx);
5919 mine_transaction(&nodes[1], &closing_tx);
5920 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5921 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5923 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5924 assert_eq!(spend_txn.len(), 1);
5925 check_spends!(spend_txn[0], closing_tx);
5928 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5929 let chanmon_cfgs = create_chanmon_cfgs(2);
5930 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5931 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5932 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5933 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5935 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5937 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5938 // present in B's local commitment transaction, but none of A's commitment transactions.
5939 nodes[1].node.claim_funds(payment_preimage);
5940 check_added_monitors!(nodes[1], 1);
5941 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5943 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5944 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5945 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5947 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5948 check_added_monitors!(nodes[0], 1);
5949 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5950 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5951 check_added_monitors!(nodes[1], 1);
5953 let starting_block = nodes[1].best_block_info();
5954 let mut block = Block {
5955 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5958 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5959 connect_block(&nodes[1], &block);
5960 block.header.prev_blockhash = block.block_hash();
5962 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5963 check_closed_broadcast!(nodes[1], true);
5964 check_added_monitors!(nodes[1], 1);
5965 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5968 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5969 let chanmon_cfgs = create_chanmon_cfgs(2);
5970 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5971 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5972 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5973 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5975 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5976 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5977 check_added_monitors!(nodes[0], 1);
5979 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5981 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5982 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5983 // to "time out" the HTLC.
5985 let starting_block = nodes[1].best_block_info();
5986 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5988 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5989 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5990 header.prev_blockhash = header.block_hash();
5992 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5993 check_closed_broadcast!(nodes[0], true);
5994 check_added_monitors!(nodes[0], 1);
5995 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5998 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5999 let chanmon_cfgs = create_chanmon_cfgs(3);
6000 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6001 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6002 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6003 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6005 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6006 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6007 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6008 // actually revoked.
6009 let htlc_value = if use_dust { 50000 } else { 3000000 };
6010 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6011 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6012 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6013 check_added_monitors!(nodes[1], 1);
6015 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6016 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6017 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6018 check_added_monitors!(nodes[0], 1);
6019 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6020 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6021 check_added_monitors!(nodes[1], 1);
6022 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6023 check_added_monitors!(nodes[1], 1);
6024 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6026 if check_revoke_no_close {
6027 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6028 check_added_monitors!(nodes[0], 1);
6031 let starting_block = nodes[1].best_block_info();
6032 let mut block = Block {
6033 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
6036 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6037 connect_block(&nodes[0], &block);
6038 block.header.prev_blockhash = block.block_hash();
6040 if !check_revoke_no_close {
6041 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6042 check_closed_broadcast!(nodes[0], true);
6043 check_added_monitors!(nodes[0], 1);
6044 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6046 let events = nodes[0].node.get_and_clear_pending_events();
6047 assert_eq!(events.len(), 2);
6048 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6049 assert_eq!(*payment_hash, our_payment_hash);
6050 } else { panic!("Unexpected event"); }
6051 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6052 assert_eq!(*payment_hash, our_payment_hash);
6053 } else { panic!("Unexpected event"); }
6057 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6058 // There are only a few cases to test here:
6059 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6060 // broadcastable commitment transactions result in channel closure,
6061 // * its included in an unrevoked-but-previous remote commitment transaction,
6062 // * its included in the latest remote or local commitment transactions.
6063 // We test each of the three possible commitment transactions individually and use both dust and
6065 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6066 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6067 // tested for at least one of the cases in other tests.
6069 fn htlc_claim_single_commitment_only_a() {
6070 do_htlc_claim_local_commitment_only(true);
6071 do_htlc_claim_local_commitment_only(false);
6073 do_htlc_claim_current_remote_commitment_only(true);
6074 do_htlc_claim_current_remote_commitment_only(false);
6078 fn htlc_claim_single_commitment_only_b() {
6079 do_htlc_claim_previous_remote_commitment_only(true, false);
6080 do_htlc_claim_previous_remote_commitment_only(false, false);
6081 do_htlc_claim_previous_remote_commitment_only(true, true);
6082 do_htlc_claim_previous_remote_commitment_only(false, true);
6087 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6088 let chanmon_cfgs = create_chanmon_cfgs(2);
6089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6091 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6092 // Force duplicate randomness for every get-random call
6093 for node in nodes.iter() {
6094 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6097 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6098 let channel_value_satoshis=10000;
6099 let push_msat=10001;
6100 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6101 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6102 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6103 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6105 // Create a second channel with the same random values. This used to panic due to a colliding
6106 // channel_id, but now panics due to a colliding outbound SCID alias.
6107 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6111 fn bolt2_open_channel_sending_node_checks_part2() {
6112 let chanmon_cfgs = create_chanmon_cfgs(2);
6113 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6114 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6115 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6117 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6118 let channel_value_satoshis=2^24;
6119 let push_msat=10001;
6120 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6122 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6123 let channel_value_satoshis=10000;
6124 // Test when push_msat is equal to 1000 * funding_satoshis.
6125 let push_msat=1000*channel_value_satoshis+1;
6126 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6128 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6129 let channel_value_satoshis=10000;
6130 let push_msat=10001;
6131 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
6132 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6133 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6135 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6136 // 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
6137 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6139 // 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.
6140 assert!(BREAKDOWN_TIMEOUT>0);
6141 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6143 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6144 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6145 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6147 // 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.
6148 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6149 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6150 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6151 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6152 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6156 fn bolt2_open_channel_sane_dust_limit() {
6157 let chanmon_cfgs = create_chanmon_cfgs(2);
6158 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6159 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6160 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6162 let channel_value_satoshis=1000000;
6163 let push_msat=10001;
6164 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6165 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6166 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6167 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6169 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6170 let events = nodes[1].node.get_and_clear_pending_msg_events();
6171 let err_msg = match events[0] {
6172 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6175 _ => panic!("Unexpected event"),
6177 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6180 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6181 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6182 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6183 // is no longer affordable once it's freed.
6185 fn test_fail_holding_cell_htlc_upon_free() {
6186 let chanmon_cfgs = create_chanmon_cfgs(2);
6187 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6188 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6189 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6190 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6192 // First nodes[0] generates an update_fee, setting the channel's
6193 // pending_update_fee.
6195 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6196 *feerate_lock += 20;
6198 nodes[0].node.timer_tick_occurred();
6199 check_added_monitors!(nodes[0], 1);
6201 let events = nodes[0].node.get_and_clear_pending_msg_events();
6202 assert_eq!(events.len(), 1);
6203 let (update_msg, commitment_signed) = match events[0] {
6204 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6205 (update_fee.as_ref(), commitment_signed)
6207 _ => panic!("Unexpected event"),
6210 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6212 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6213 let channel_reserve = chan_stat.channel_reserve_msat;
6214 let feerate = get_feerate!(nodes[0], chan.2);
6215 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6217 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6218 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6219 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6221 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6222 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6223 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6224 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6226 // Flush the pending fee update.
6227 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6228 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6229 check_added_monitors!(nodes[1], 1);
6230 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6231 check_added_monitors!(nodes[0], 1);
6233 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6234 // HTLC, but now that the fee has been raised the payment will now fail, causing
6235 // us to surface its failure to the user.
6236 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6237 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6238 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);
6239 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 {}",
6240 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6241 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6243 // Check that the payment failed to be sent out.
6244 let events = nodes[0].node.get_and_clear_pending_events();
6245 assert_eq!(events.len(), 1);
6247 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6248 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6249 assert_eq!(our_payment_hash.clone(), *payment_hash);
6250 assert_eq!(*payment_failed_permanently, false);
6251 assert_eq!(*all_paths_failed, true);
6252 assert_eq!(*network_update, None);
6253 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
6255 _ => panic!("Unexpected event"),
6259 // Test that if multiple HTLCs are released from the holding cell and one is
6260 // valid but the other is no longer valid upon release, the valid HTLC can be
6261 // successfully completed while the other one fails as expected.
6263 fn test_free_and_fail_holding_cell_htlcs() {
6264 let chanmon_cfgs = create_chanmon_cfgs(2);
6265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6267 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6268 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6270 // First nodes[0] generates an update_fee, setting the channel's
6271 // pending_update_fee.
6273 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6274 *feerate_lock += 200;
6276 nodes[0].node.timer_tick_occurred();
6277 check_added_monitors!(nodes[0], 1);
6279 let events = nodes[0].node.get_and_clear_pending_msg_events();
6280 assert_eq!(events.len(), 1);
6281 let (update_msg, commitment_signed) = match events[0] {
6282 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6283 (update_fee.as_ref(), commitment_signed)
6285 _ => panic!("Unexpected event"),
6288 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6290 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6291 let channel_reserve = chan_stat.channel_reserve_msat;
6292 let feerate = get_feerate!(nodes[0], chan.2);
6293 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6295 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6297 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6298 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6299 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6301 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6302 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6303 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6304 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6305 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6306 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6307 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6309 // Flush the pending fee update.
6310 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6311 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6312 check_added_monitors!(nodes[1], 1);
6313 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6314 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6315 check_added_monitors!(nodes[0], 2);
6317 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6318 // but now that the fee has been raised the second payment will now fail, causing us
6319 // to surface its failure to the user. The first payment should succeed.
6320 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6321 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6322 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);
6323 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 {}",
6324 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6325 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6327 // Check that the second payment failed to be sent out.
6328 let events = nodes[0].node.get_and_clear_pending_events();
6329 assert_eq!(events.len(), 1);
6331 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6332 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6333 assert_eq!(payment_hash_2.clone(), *payment_hash);
6334 assert_eq!(*payment_failed_permanently, false);
6335 assert_eq!(*all_paths_failed, true);
6336 assert_eq!(*network_update, None);
6337 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
6339 _ => panic!("Unexpected event"),
6342 // Complete the first payment and the RAA from the fee update.
6343 let (payment_event, send_raa_event) = {
6344 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6345 assert_eq!(msgs.len(), 2);
6346 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6348 let raa = match send_raa_event {
6349 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6350 _ => panic!("Unexpected event"),
6352 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6353 check_added_monitors!(nodes[1], 1);
6354 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6355 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6356 let events = nodes[1].node.get_and_clear_pending_events();
6357 assert_eq!(events.len(), 1);
6359 Event::PendingHTLCsForwardable { .. } => {},
6360 _ => panic!("Unexpected event"),
6362 nodes[1].node.process_pending_htlc_forwards();
6363 let events = nodes[1].node.get_and_clear_pending_events();
6364 assert_eq!(events.len(), 1);
6366 Event::PaymentReceived { .. } => {},
6367 _ => panic!("Unexpected event"),
6369 nodes[1].node.claim_funds(payment_preimage_1);
6370 check_added_monitors!(nodes[1], 1);
6371 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6373 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6374 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6375 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6376 expect_payment_sent!(nodes[0], payment_preimage_1);
6379 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6380 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6381 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6384 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6385 let chanmon_cfgs = create_chanmon_cfgs(3);
6386 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6387 // When this test was written, the default base fee floated based on the HTLC count.
6388 // It is now fixed, so we simply set the fee to the expected value here.
6389 let mut config = test_default_channel_config();
6390 config.channel_config.forwarding_fee_base_msat = 196;
6391 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6392 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6393 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6394 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6396 // First nodes[1] generates an update_fee, setting the channel's
6397 // pending_update_fee.
6399 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6400 *feerate_lock += 20;
6402 nodes[1].node.timer_tick_occurred();
6403 check_added_monitors!(nodes[1], 1);
6405 let events = nodes[1].node.get_and_clear_pending_msg_events();
6406 assert_eq!(events.len(), 1);
6407 let (update_msg, commitment_signed) = match events[0] {
6408 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6409 (update_fee.as_ref(), commitment_signed)
6411 _ => panic!("Unexpected event"),
6414 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6416 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6417 let channel_reserve = chan_stat.channel_reserve_msat;
6418 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6419 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6421 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6423 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6424 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6425 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6426 let payment_event = {
6427 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6428 check_added_monitors!(nodes[0], 1);
6430 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6431 assert_eq!(events.len(), 1);
6433 SendEvent::from_event(events.remove(0))
6435 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6436 check_added_monitors!(nodes[1], 0);
6437 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6438 expect_pending_htlcs_forwardable!(nodes[1]);
6440 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6441 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6443 // Flush the pending fee update.
6444 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6445 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6446 check_added_monitors!(nodes[2], 1);
6447 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6448 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6449 check_added_monitors!(nodes[1], 2);
6451 // A final RAA message is generated to finalize the fee update.
6452 let events = nodes[1].node.get_and_clear_pending_msg_events();
6453 assert_eq!(events.len(), 1);
6455 let raa_msg = match &events[0] {
6456 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6459 _ => panic!("Unexpected event"),
6462 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6463 check_added_monitors!(nodes[2], 1);
6464 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6466 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6467 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6468 assert_eq!(process_htlc_forwards_event.len(), 2);
6469 match &process_htlc_forwards_event[0] {
6470 &Event::PendingHTLCsForwardable { .. } => {},
6471 _ => panic!("Unexpected event"),
6474 // In response, we call ChannelManager's process_pending_htlc_forwards
6475 nodes[1].node.process_pending_htlc_forwards();
6476 check_added_monitors!(nodes[1], 1);
6478 // This causes the HTLC to be failed backwards.
6479 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6480 assert_eq!(fail_event.len(), 1);
6481 let (fail_msg, commitment_signed) = match &fail_event[0] {
6482 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6483 assert_eq!(updates.update_add_htlcs.len(), 0);
6484 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6485 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6486 assert_eq!(updates.update_fail_htlcs.len(), 1);
6487 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6489 _ => panic!("Unexpected event"),
6492 // Pass the failure messages back to nodes[0].
6493 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6494 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6496 // Complete the HTLC failure+removal process.
6497 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6498 check_added_monitors!(nodes[0], 1);
6499 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6500 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6501 check_added_monitors!(nodes[1], 2);
6502 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6503 assert_eq!(final_raa_event.len(), 1);
6504 let raa = match &final_raa_event[0] {
6505 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6506 _ => panic!("Unexpected event"),
6508 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6509 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6510 check_added_monitors!(nodes[0], 1);
6513 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6514 // 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.
6515 //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.
6518 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6519 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6520 let chanmon_cfgs = create_chanmon_cfgs(2);
6521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6523 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6524 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6526 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6527 route.paths[0][0].fee_msat = 100;
6529 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6530 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6531 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6532 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6536 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6537 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
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 = 0;
6546 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6547 assert_eq!(err, "Cannot send 0-msat HTLC"));
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 0-msat HTLC".to_string(), 1);
6554 fn test_update_add_htlc_bolt2_receiver_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 (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6563 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6564 check_added_monitors!(nodes[0], 1);
6565 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6566 updates.update_add_htlcs[0].amount_msat = 0;
6568 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6569 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6570 check_closed_broadcast!(nodes[1], true).unwrap();
6571 check_added_monitors!(nodes[1], 1);
6572 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6576 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6577 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6578 //It is enforced when constructing a route.
6579 let chanmon_cfgs = create_chanmon_cfgs(2);
6580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6582 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6583 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6585 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6586 .with_features(channelmanager::provided_invoice_features());
6587 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6588 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6589 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6590 assert_eq!(err, &"Channel CLTV overflowed?"));
6594 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6595 //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.
6596 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6597 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6598 let chanmon_cfgs = create_chanmon_cfgs(2);
6599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6601 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6602 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6603 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6605 for i in 0..max_accepted_htlcs {
6606 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6607 let payment_event = {
6608 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6609 check_added_monitors!(nodes[0], 1);
6611 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6612 assert_eq!(events.len(), 1);
6613 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6614 assert_eq!(htlcs[0].htlc_id, i);
6618 SendEvent::from_event(events.remove(0))
6620 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6621 check_added_monitors!(nodes[1], 0);
6622 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6624 expect_pending_htlcs_forwardable!(nodes[1]);
6625 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6627 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6628 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6629 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6631 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6632 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6636 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6637 //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.
6638 let chanmon_cfgs = create_chanmon_cfgs(2);
6639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6641 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6642 let channel_value = 100000;
6643 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6644 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6646 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6648 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6649 // Manually create a route over our max in flight (which our router normally automatically
6651 route.paths[0][0].fee_msat = max_in_flight + 1;
6652 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6653 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)));
6655 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6656 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);
6658 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6661 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6663 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6664 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6665 let chanmon_cfgs = create_chanmon_cfgs(2);
6666 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6667 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6668 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6669 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6670 let htlc_minimum_msat: u64;
6672 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6673 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6674 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6677 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6678 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6679 check_added_monitors!(nodes[0], 1);
6680 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6681 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6682 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6683 assert!(nodes[1].node.list_channels().is_empty());
6684 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6685 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()));
6686 check_added_monitors!(nodes[1], 1);
6687 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6691 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6692 //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
6693 let chanmon_cfgs = create_chanmon_cfgs(2);
6694 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6695 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6696 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6697 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6699 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6700 let channel_reserve = chan_stat.channel_reserve_msat;
6701 let feerate = get_feerate!(nodes[0], chan.2);
6702 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6703 // The 2* and +1 are for the fee spike reserve.
6704 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6706 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6707 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6708 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6709 check_added_monitors!(nodes[0], 1);
6710 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6712 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6713 // at this time channel-initiatee receivers are not required to enforce that senders
6714 // respect the fee_spike_reserve.
6715 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6716 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6718 assert!(nodes[1].node.list_channels().is_empty());
6719 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6720 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6721 check_added_monitors!(nodes[1], 1);
6722 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6726 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6727 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6728 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6729 let chanmon_cfgs = create_chanmon_cfgs(2);
6730 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6731 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6732 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6733 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6735 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6736 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6737 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6738 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6739 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6740 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6742 let mut msg = msgs::UpdateAddHTLC {
6746 payment_hash: our_payment_hash,
6747 cltv_expiry: htlc_cltv,
6748 onion_routing_packet: onion_packet.clone(),
6751 for i in 0..super::channel::OUR_MAX_HTLCS {
6752 msg.htlc_id = i as u64;
6753 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6755 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6756 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6758 assert!(nodes[1].node.list_channels().is_empty());
6759 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6760 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6761 check_added_monitors!(nodes[1], 1);
6762 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6766 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6767 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6768 let chanmon_cfgs = create_chanmon_cfgs(2);
6769 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6770 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6771 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6772 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6774 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6775 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6776 check_added_monitors!(nodes[0], 1);
6777 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6778 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6779 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6781 assert!(nodes[1].node.list_channels().is_empty());
6782 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6783 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6784 check_added_monitors!(nodes[1], 1);
6785 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6789 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6790 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6791 let chanmon_cfgs = create_chanmon_cfgs(2);
6792 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6793 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6794 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6796 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6797 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6798 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6799 check_added_monitors!(nodes[0], 1);
6800 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6801 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6802 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6804 assert!(nodes[1].node.list_channels().is_empty());
6805 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6806 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6807 check_added_monitors!(nodes[1], 1);
6808 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6812 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6813 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6814 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6815 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6816 let chanmon_cfgs = create_chanmon_cfgs(2);
6817 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6818 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6819 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6821 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6822 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6823 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6824 check_added_monitors!(nodes[0], 1);
6825 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6826 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6828 //Disconnect and Reconnect
6829 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6830 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6831 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6832 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6833 assert_eq!(reestablish_1.len(), 1);
6834 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6835 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6836 assert_eq!(reestablish_2.len(), 1);
6837 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6838 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6839 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6840 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6843 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6844 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6845 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6846 check_added_monitors!(nodes[1], 1);
6847 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6849 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6851 assert!(nodes[1].node.list_channels().is_empty());
6852 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6853 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6854 check_added_monitors!(nodes[1], 1);
6855 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6859 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6860 //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.
6862 let chanmon_cfgs = create_chanmon_cfgs(2);
6863 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6864 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6865 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6866 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6867 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6868 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6870 check_added_monitors!(nodes[0], 1);
6871 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6872 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6874 let update_msg = msgs::UpdateFulfillHTLC{
6877 payment_preimage: our_payment_preimage,
6880 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6882 assert!(nodes[0].node.list_channels().is_empty());
6883 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6884 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()));
6885 check_added_monitors!(nodes[0], 1);
6886 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6890 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6891 //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.
6893 let chanmon_cfgs = create_chanmon_cfgs(2);
6894 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6895 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6896 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6897 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6899 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6900 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6901 check_added_monitors!(nodes[0], 1);
6902 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6903 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6905 let update_msg = msgs::UpdateFailHTLC{
6908 reason: msgs::OnionErrorPacket { data: Vec::new()},
6911 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6913 assert!(nodes[0].node.list_channels().is_empty());
6914 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6915 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()));
6916 check_added_monitors!(nodes[0], 1);
6917 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6921 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6922 //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.
6924 let chanmon_cfgs = create_chanmon_cfgs(2);
6925 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6926 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6927 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6928 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6930 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6931 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6932 check_added_monitors!(nodes[0], 1);
6933 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6934 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6935 let update_msg = msgs::UpdateFailMalformedHTLC{
6938 sha256_of_onion: [1; 32],
6939 failure_code: 0x8000,
6942 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6944 assert!(nodes[0].node.list_channels().is_empty());
6945 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6946 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()));
6947 check_added_monitors!(nodes[0], 1);
6948 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6952 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6953 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6955 let chanmon_cfgs = create_chanmon_cfgs(2);
6956 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6958 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6959 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6961 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6963 nodes[1].node.claim_funds(our_payment_preimage);
6964 check_added_monitors!(nodes[1], 1);
6965 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6967 let events = nodes[1].node.get_and_clear_pending_msg_events();
6968 assert_eq!(events.len(), 1);
6969 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6971 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, .. } } => {
6972 assert!(update_add_htlcs.is_empty());
6973 assert_eq!(update_fulfill_htlcs.len(), 1);
6974 assert!(update_fail_htlcs.is_empty());
6975 assert!(update_fail_malformed_htlcs.is_empty());
6976 assert!(update_fee.is_none());
6977 update_fulfill_htlcs[0].clone()
6979 _ => panic!("Unexpected event"),
6983 update_fulfill_msg.htlc_id = 1;
6985 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6987 assert!(nodes[0].node.list_channels().is_empty());
6988 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6989 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6990 check_added_monitors!(nodes[0], 1);
6991 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6995 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6996 //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.
6998 let chanmon_cfgs = create_chanmon_cfgs(2);
6999 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7000 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7001 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7002 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7004 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7006 nodes[1].node.claim_funds(our_payment_preimage);
7007 check_added_monitors!(nodes[1], 1);
7008 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7010 let events = nodes[1].node.get_and_clear_pending_msg_events();
7011 assert_eq!(events.len(), 1);
7012 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7014 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, .. } } => {
7015 assert!(update_add_htlcs.is_empty());
7016 assert_eq!(update_fulfill_htlcs.len(), 1);
7017 assert!(update_fail_htlcs.is_empty());
7018 assert!(update_fail_malformed_htlcs.is_empty());
7019 assert!(update_fee.is_none());
7020 update_fulfill_htlcs[0].clone()
7022 _ => panic!("Unexpected event"),
7026 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7028 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7030 assert!(nodes[0].node.list_channels().is_empty());
7031 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7032 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7033 check_added_monitors!(nodes[0], 1);
7034 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7038 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7039 //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.
7041 let chanmon_cfgs = create_chanmon_cfgs(2);
7042 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7043 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7044 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7045 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7047 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7048 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7049 check_added_monitors!(nodes[0], 1);
7051 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7052 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7054 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7055 check_added_monitors!(nodes[1], 0);
7056 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7058 let events = nodes[1].node.get_and_clear_pending_msg_events();
7060 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7062 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, .. } } => {
7063 assert!(update_add_htlcs.is_empty());
7064 assert!(update_fulfill_htlcs.is_empty());
7065 assert!(update_fail_htlcs.is_empty());
7066 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7067 assert!(update_fee.is_none());
7068 update_fail_malformed_htlcs[0].clone()
7070 _ => panic!("Unexpected event"),
7073 update_msg.failure_code &= !0x8000;
7074 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7076 assert!(nodes[0].node.list_channels().is_empty());
7077 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7078 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7079 check_added_monitors!(nodes[0], 1);
7080 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7084 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7085 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7086 // * 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.
7088 let chanmon_cfgs = create_chanmon_cfgs(3);
7089 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7090 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7091 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7092 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7093 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7095 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7098 let mut payment_event = {
7099 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7100 check_added_monitors!(nodes[0], 1);
7101 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7102 assert_eq!(events.len(), 1);
7103 SendEvent::from_event(events.remove(0))
7105 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7106 check_added_monitors!(nodes[1], 0);
7107 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7108 expect_pending_htlcs_forwardable!(nodes[1]);
7109 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7110 assert_eq!(events_2.len(), 1);
7111 check_added_monitors!(nodes[1], 1);
7112 payment_event = SendEvent::from_event(events_2.remove(0));
7113 assert_eq!(payment_event.msgs.len(), 1);
7116 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7117 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7118 check_added_monitors!(nodes[2], 0);
7119 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7121 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7122 assert_eq!(events_3.len(), 1);
7123 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7125 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 } } => {
7126 assert!(update_add_htlcs.is_empty());
7127 assert!(update_fulfill_htlcs.is_empty());
7128 assert!(update_fail_htlcs.is_empty());
7129 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7130 assert!(update_fee.is_none());
7131 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7133 _ => panic!("Unexpected event"),
7137 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7139 check_added_monitors!(nodes[1], 0);
7140 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7141 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 }]);
7142 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7143 assert_eq!(events_4.len(), 1);
7145 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7147 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, .. } } => {
7148 assert!(update_add_htlcs.is_empty());
7149 assert!(update_fulfill_htlcs.is_empty());
7150 assert_eq!(update_fail_htlcs.len(), 1);
7151 assert!(update_fail_malformed_htlcs.is_empty());
7152 assert!(update_fee.is_none());
7154 _ => panic!("Unexpected event"),
7157 check_added_monitors!(nodes[1], 1);
7161 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
7162 let chanmon_cfgs = create_chanmon_cfgs(3);
7163 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7164 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7165 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7166 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7167 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7169 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
7172 let mut payment_event = {
7173 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7174 check_added_monitors!(nodes[0], 1);
7175 SendEvent::from_node(&nodes[0])
7178 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7179 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7180 expect_pending_htlcs_forwardable!(nodes[1]);
7181 check_added_monitors!(nodes[1], 1);
7182 payment_event = SendEvent::from_node(&nodes[1]);
7183 assert_eq!(payment_event.msgs.len(), 1);
7186 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
7187 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7188 check_added_monitors!(nodes[2], 0);
7189 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7191 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7192 assert_eq!(events_3.len(), 1);
7194 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7195 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7196 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7197 update_msg.failure_code |= 0x2000;
7199 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7200 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7202 _ => panic!("Unexpected event"),
7205 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7206 vec![HTLCDestination::NextHopChannel {
7207 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7208 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7209 assert_eq!(events_4.len(), 1);
7210 check_added_monitors!(nodes[1], 1);
7213 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7215 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7217 _ => panic!("Unexpected event"),
7220 let events_5 = nodes[0].node.get_and_clear_pending_events();
7221 assert_eq!(events_5.len(), 1);
7223 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7224 // the node originating the error to its next hop.
7226 Event::PaymentPathFailed { network_update:
7227 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
7229 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7230 assert!(is_permanent);
7231 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7233 _ => panic!("Unexpected event"),
7236 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7239 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7240 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7241 // 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
7242 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7244 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7245 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7249 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7251 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7253 // We route 2 dust-HTLCs between A and B
7254 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7255 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7256 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7258 // Cache one local commitment tx as previous
7259 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7261 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7262 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7263 check_added_monitors!(nodes[1], 0);
7264 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7265 check_added_monitors!(nodes[1], 1);
7267 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7268 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7269 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7270 check_added_monitors!(nodes[0], 1);
7272 // Cache one local commitment tx as lastest
7273 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7275 let events = nodes[0].node.get_and_clear_pending_msg_events();
7277 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7278 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7280 _ => panic!("Unexpected event"),
7283 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7284 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7286 _ => panic!("Unexpected event"),
7289 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7290 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7291 if announce_latest {
7292 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7294 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7297 check_closed_broadcast!(nodes[0], true);
7298 check_added_monitors!(nodes[0], 1);
7299 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7301 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7302 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7303 let events = nodes[0].node.get_and_clear_pending_events();
7304 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7305 assert_eq!(events.len(), 2);
7306 let mut first_failed = false;
7307 for event in events {
7309 Event::PaymentPathFailed { payment_hash, .. } => {
7310 if payment_hash == payment_hash_1 {
7311 assert!(!first_failed);
7312 first_failed = true;
7314 assert_eq!(payment_hash, payment_hash_2);
7317 _ => panic!("Unexpected event"),
7323 fn test_failure_delay_dust_htlc_local_commitment() {
7324 do_test_failure_delay_dust_htlc_local_commitment(true);
7325 do_test_failure_delay_dust_htlc_local_commitment(false);
7328 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7329 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7330 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7331 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7332 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7333 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7334 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7336 let chanmon_cfgs = create_chanmon_cfgs(3);
7337 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7338 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7339 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7340 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7342 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7344 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7345 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7347 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7348 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7350 // We revoked bs_commitment_tx
7352 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7353 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7356 let mut timeout_tx = Vec::new();
7358 // We fail dust-HTLC 1 by broadcast of local commitment tx
7359 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7360 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7361 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7362 expect_payment_failed!(nodes[0], dust_hash, false);
7364 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7365 check_closed_broadcast!(nodes[0], true);
7366 check_added_monitors!(nodes[0], 1);
7367 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7368 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7369 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7370 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7371 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7372 mine_transaction(&nodes[0], &timeout_tx[0]);
7373 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7374 expect_payment_failed!(nodes[0], non_dust_hash, false);
7376 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7377 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7378 check_closed_broadcast!(nodes[0], true);
7379 check_added_monitors!(nodes[0], 1);
7380 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7381 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7383 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7384 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7385 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7386 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7387 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7388 // dust HTLC should have been failed.
7389 expect_payment_failed!(nodes[0], dust_hash, false);
7392 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7394 assert_eq!(timeout_tx[0].lock_time.0, 0);
7396 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7397 mine_transaction(&nodes[0], &timeout_tx[0]);
7398 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7399 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7400 expect_payment_failed!(nodes[0], non_dust_hash, false);
7405 fn test_sweep_outbound_htlc_failure_update() {
7406 do_test_sweep_outbound_htlc_failure_update(false, true);
7407 do_test_sweep_outbound_htlc_failure_update(false, false);
7408 do_test_sweep_outbound_htlc_failure_update(true, false);
7412 fn test_user_configurable_csv_delay() {
7413 // We test our channel constructors yield errors when we pass them absurd csv delay
7415 let mut low_our_to_self_config = UserConfig::default();
7416 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7417 let mut high_their_to_self_config = UserConfig::default();
7418 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7419 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7420 let chanmon_cfgs = create_chanmon_cfgs(2);
7421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7422 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7423 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7425 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7426 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7427 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
7428 &low_our_to_self_config, 0, 42)
7431 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())); },
7432 _ => panic!("Unexpected event"),
7434 } else { assert!(false) }
7436 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7437 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7438 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7439 open_channel.to_self_delay = 200;
7440 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7441 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7442 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7445 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())); },
7446 _ => panic!("Unexpected event"),
7448 } else { assert!(false); }
7450 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7451 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7452 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()));
7453 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7454 accept_channel.to_self_delay = 200;
7455 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
7457 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7459 &ErrorAction::SendErrorMessage { ref msg } => {
7460 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()));
7461 reason_msg = msg.data.clone();
7465 } else { panic!(); }
7466 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7468 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7469 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7470 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7471 open_channel.to_self_delay = 200;
7472 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7473 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7474 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7477 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())); },
7478 _ => panic!("Unexpected event"),
7480 } else { assert!(false); }
7483 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7484 // When we get a data_loss_protect proving we're behind, we immediately panic as the
7485 // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7486 // panic message informs the user they should force-close without broadcasting, which is tested
7487 // if `reconnect_panicing` is not set.
7493 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7494 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7495 // during signing due to revoked tx
7496 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7497 let keys_manager = &chanmon_cfgs[0].keys_manager;
7500 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7501 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7502 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7504 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7506 // Cache node A state before any channel update
7507 let previous_node_state = nodes[0].node.encode();
7508 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7509 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7511 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7512 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7514 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7515 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7517 // Restore node A from previous state
7518 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7519 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7520 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7521 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7522 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7523 persister = test_utils::TestPersister::new();
7524 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7526 let mut channel_monitors = HashMap::new();
7527 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7528 <(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 {
7529 keys_manager: keys_manager,
7530 fee_estimator: &fee_estimator,
7531 chain_monitor: &monitor,
7533 tx_broadcaster: &tx_broadcaster,
7534 default_config: UserConfig::default(),
7538 nodes[0].node = &node_state_0;
7539 assert_eq!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor),
7540 ChannelMonitorUpdateStatus::Completed);
7541 nodes[0].chain_monitor = &monitor;
7542 nodes[0].chain_source = &chain_source;
7544 check_added_monitors!(nodes[0], 1);
7546 if reconnect_panicing {
7547 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7548 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7550 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7552 // Check we close channel detecting A is fallen-behind
7553 // Check that we sent the warning message when we detected that A has fallen behind,
7554 // and give the possibility for A to recover from the warning.
7555 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7556 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7557 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7560 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7561 // The node B should not broadcast the transaction to force close the channel!
7562 assert!(node_txn.is_empty());
7565 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7566 // Check A panics upon seeing proof it has fallen behind.
7567 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7568 return; // By this point we should have panic'ed!
7571 nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7572 check_added_monitors!(nodes[0], 1);
7573 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7575 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7576 assert_eq!(node_txn.len(), 0);
7579 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7580 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7581 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7583 &ErrorAction::SendErrorMessage { ref msg } => {
7584 assert_eq!(msg.data, "Channel force-closed");
7586 _ => panic!("Unexpected event!"),
7589 panic!("Unexpected event {:?}", msg)
7593 // after the warning message sent by B, we should not able to
7594 // use the channel, or reconnect with success to the channel.
7595 assert!(nodes[0].node.list_usable_channels().is_empty());
7596 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7597 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7598 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7600 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7601 let mut err_msgs_0 = Vec::with_capacity(1);
7602 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7603 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7605 &ErrorAction::SendErrorMessage { ref msg } => {
7606 assert_eq!(msg.data, "Failed to find corresponding channel");
7607 err_msgs_0.push(msg.clone());
7609 _ => panic!("Unexpected event!"),
7612 panic!("Unexpected event!");
7615 assert_eq!(err_msgs_0.len(), 1);
7616 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7617 assert!(nodes[1].node.list_usable_channels().is_empty());
7618 check_added_monitors!(nodes[1], 1);
7619 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7620 check_closed_broadcast!(nodes[1], false);
7625 fn test_data_loss_protect_showing_stale_state_panics() {
7626 do_test_data_loss_protect(true);
7630 fn test_force_close_without_broadcast() {
7631 do_test_data_loss_protect(false);
7635 fn test_check_htlc_underpaying() {
7636 // Send payment through A -> B but A is maliciously
7637 // sending a probe payment (i.e less than expected value0
7638 // to B, B should refuse payment.
7640 let chanmon_cfgs = create_chanmon_cfgs(2);
7641 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7642 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7643 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7645 // Create some initial channels
7646 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7648 let scorer = test_utils::TestScorer::with_penalty(0);
7649 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7650 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7651 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();
7652 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7653 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7654 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7655 check_added_monitors!(nodes[0], 1);
7657 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7658 assert_eq!(events.len(), 1);
7659 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7660 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7661 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7663 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7664 // and then will wait a second random delay before failing the HTLC back:
7665 expect_pending_htlcs_forwardable!(nodes[1]);
7666 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7668 // Node 3 is expecting payment of 100_000 but received 10_000,
7669 // it should fail htlc like we didn't know the preimage.
7670 nodes[1].node.process_pending_htlc_forwards();
7672 let events = nodes[1].node.get_and_clear_pending_msg_events();
7673 assert_eq!(events.len(), 1);
7674 let (update_fail_htlc, commitment_signed) = match events[0] {
7675 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 } } => {
7676 assert!(update_add_htlcs.is_empty());
7677 assert!(update_fulfill_htlcs.is_empty());
7678 assert_eq!(update_fail_htlcs.len(), 1);
7679 assert!(update_fail_malformed_htlcs.is_empty());
7680 assert!(update_fee.is_none());
7681 (update_fail_htlcs[0].clone(), commitment_signed)
7683 _ => panic!("Unexpected event"),
7685 check_added_monitors!(nodes[1], 1);
7687 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7688 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7690 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7691 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7692 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7693 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7697 fn test_announce_disable_channels() {
7698 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7699 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7701 let chanmon_cfgs = create_chanmon_cfgs(2);
7702 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7703 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7704 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7706 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7707 create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7708 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7711 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7712 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7714 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7715 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7716 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7717 assert_eq!(msg_events.len(), 3);
7718 let mut chans_disabled = HashMap::new();
7719 for e in msg_events {
7721 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7722 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7723 // Check that each channel gets updated exactly once
7724 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7725 panic!("Generated ChannelUpdate for wrong chan!");
7728 _ => panic!("Unexpected event"),
7732 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7733 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7734 assert_eq!(reestablish_1.len(), 3);
7735 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7736 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7737 assert_eq!(reestablish_2.len(), 3);
7739 // Reestablish chan_1
7740 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7741 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7742 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7743 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7744 // Reestablish chan_2
7745 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7746 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7747 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7748 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7749 // Reestablish chan_3
7750 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7751 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7752 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7753 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7755 nodes[0].node.timer_tick_occurred();
7756 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7757 nodes[0].node.timer_tick_occurred();
7758 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7759 assert_eq!(msg_events.len(), 3);
7760 for e in msg_events {
7762 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7763 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7764 match chans_disabled.remove(&msg.contents.short_channel_id) {
7765 // Each update should have a higher timestamp than the previous one, replacing
7767 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7768 None => panic!("Generated ChannelUpdate for wrong chan!"),
7771 _ => panic!("Unexpected event"),
7774 // Check that each channel gets updated exactly once
7775 assert!(chans_disabled.is_empty());
7779 fn test_bump_penalty_txn_on_revoked_commitment() {
7780 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7781 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7783 let chanmon_cfgs = create_chanmon_cfgs(2);
7784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7788 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7790 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7791 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7792 .with_features(channelmanager::provided_invoice_features());
7793 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7794 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7796 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7797 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7798 assert_eq!(revoked_txn[0].output.len(), 4);
7799 assert_eq!(revoked_txn[0].input.len(), 1);
7800 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7801 let revoked_txid = revoked_txn[0].txid();
7803 let mut penalty_sum = 0;
7804 for outp in revoked_txn[0].output.iter() {
7805 if outp.script_pubkey.is_v0_p2wsh() {
7806 penalty_sum += outp.value;
7810 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7811 let header_114 = connect_blocks(&nodes[1], 14);
7813 // Actually revoke tx by claiming a HTLC
7814 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7815 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7816 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7817 check_added_monitors!(nodes[1], 1);
7819 // One or more justice tx should have been broadcast, check it
7823 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7824 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7825 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7826 assert_eq!(node_txn[0].output.len(), 1);
7827 check_spends!(node_txn[0], revoked_txn[0]);
7828 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7829 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7830 penalty_1 = node_txn[0].txid();
7834 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7835 connect_blocks(&nodes[1], 15);
7836 let mut penalty_2 = penalty_1;
7837 let mut feerate_2 = 0;
7839 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7840 assert_eq!(node_txn.len(), 1);
7841 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7842 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7843 assert_eq!(node_txn[0].output.len(), 1);
7844 check_spends!(node_txn[0], revoked_txn[0]);
7845 penalty_2 = node_txn[0].txid();
7846 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7847 assert_ne!(penalty_2, penalty_1);
7848 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7849 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7850 // Verify 25% bump heuristic
7851 assert!(feerate_2 * 100 >= feerate_1 * 125);
7855 assert_ne!(feerate_2, 0);
7857 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7858 connect_blocks(&nodes[1], 1);
7860 let mut feerate_3 = 0;
7862 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7863 assert_eq!(node_txn.len(), 1);
7864 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7865 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7866 assert_eq!(node_txn[0].output.len(), 1);
7867 check_spends!(node_txn[0], revoked_txn[0]);
7868 penalty_3 = node_txn[0].txid();
7869 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7870 assert_ne!(penalty_3, penalty_2);
7871 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7872 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7873 // Verify 25% bump heuristic
7874 assert!(feerate_3 * 100 >= feerate_2 * 125);
7878 assert_ne!(feerate_3, 0);
7880 nodes[1].node.get_and_clear_pending_events();
7881 nodes[1].node.get_and_clear_pending_msg_events();
7885 fn test_bump_penalty_txn_on_revoked_htlcs() {
7886 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7887 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7889 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7890 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7891 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7892 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7893 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7895 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7896 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7897 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7898 let scorer = test_utils::TestScorer::with_penalty(0);
7899 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7900 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7901 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7902 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7903 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7904 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7905 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7906 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7908 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7909 assert_eq!(revoked_local_txn[0].input.len(), 1);
7910 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7912 // Revoke local commitment tx
7913 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7915 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7916 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7917 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7918 check_closed_broadcast!(nodes[1], true);
7919 check_added_monitors!(nodes[1], 1);
7920 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7921 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7923 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7924 assert_eq!(revoked_htlc_txn.len(), 3);
7925 check_spends!(revoked_htlc_txn[1], chan.3);
7927 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7928 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7929 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7931 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7932 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7933 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7934 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7936 // Broadcast set of revoked txn on A
7937 let hash_128 = connect_blocks(&nodes[0], 40);
7938 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7939 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7940 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7941 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7942 let events = nodes[0].node.get_and_clear_pending_events();
7943 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7944 match events.last().unwrap() {
7945 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7946 _ => panic!("Unexpected event"),
7952 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7953 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7954 // Verify claim tx are spending revoked HTLC txn
7956 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7957 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7958 // which are included in the same block (they are broadcasted because we scan the
7959 // transactions linearly and generate claims as we go, they likely should be removed in the
7961 assert_eq!(node_txn[0].input.len(), 1);
7962 check_spends!(node_txn[0], revoked_local_txn[0]);
7963 assert_eq!(node_txn[1].input.len(), 1);
7964 check_spends!(node_txn[1], revoked_local_txn[0]);
7965 assert_eq!(node_txn[2].input.len(), 1);
7966 check_spends!(node_txn[2], revoked_local_txn[0]);
7968 // Each of the three justice transactions claim a separate (single) output of the three
7969 // available, which we check here:
7970 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7971 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7972 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7974 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7975 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7977 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7978 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7979 // a remote commitment tx has already been confirmed).
7980 check_spends!(node_txn[3], chan.3);
7982 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7983 // output, checked above).
7984 assert_eq!(node_txn[4].input.len(), 2);
7985 assert_eq!(node_txn[4].output.len(), 1);
7986 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7988 first = node_txn[4].txid();
7989 // Store both feerates for later comparison
7990 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7991 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7992 penalty_txn = vec![node_txn[2].clone()];
7996 // Connect one more block to see if bumped penalty are issued for HTLC txn
7997 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7998 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7999 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8000 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
8002 // Few more blocks to confirm penalty txn
8003 connect_blocks(&nodes[0], 4);
8004 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8005 let header_144 = connect_blocks(&nodes[0], 9);
8007 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8008 assert_eq!(node_txn.len(), 1);
8010 assert_eq!(node_txn[0].input.len(), 2);
8011 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8012 // Verify bumped tx is different and 25% bump heuristic
8013 assert_ne!(first, node_txn[0].txid());
8014 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
8015 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
8016 assert!(feerate_2 * 100 > feerate_1 * 125);
8017 let txn = vec![node_txn[0].clone()];
8021 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8022 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8023 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8024 connect_blocks(&nodes[0], 20);
8026 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8027 // We verify than no new transaction has been broadcast because previously
8028 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8029 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8030 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8031 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8032 // up bumped justice generation.
8033 assert_eq!(node_txn.len(), 0);
8036 check_closed_broadcast!(nodes[0], true);
8037 check_added_monitors!(nodes[0], 1);
8041 fn test_bump_penalty_txn_on_remote_commitment() {
8042 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8043 // we're able to claim outputs on remote commitment transaction before timelocks expiration
8046 // Provide preimage for one
8047 // Check aggregation
8049 let chanmon_cfgs = create_chanmon_cfgs(2);
8050 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8051 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8052 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8054 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8055 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8056 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8058 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8059 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8060 assert_eq!(remote_txn[0].output.len(), 4);
8061 assert_eq!(remote_txn[0].input.len(), 1);
8062 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8064 // Claim a HTLC without revocation (provide B monitor with preimage)
8065 nodes[1].node.claim_funds(payment_preimage);
8066 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8067 mine_transaction(&nodes[1], &remote_txn[0]);
8068 check_added_monitors!(nodes[1], 2);
8069 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8071 // One or more claim tx should have been broadcast, check it
8075 let feerate_timeout;
8076 let feerate_preimage;
8078 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8079 // 5 transactions including:
8080 // local commitment + HTLC-Success
8081 // preimage and timeout sweeps from remote commitment + preimage sweep bump
8082 assert_eq!(node_txn.len(), 5);
8083 assert_eq!(node_txn[0].input.len(), 1);
8084 assert_eq!(node_txn[3].input.len(), 1);
8085 assert_eq!(node_txn[4].input.len(), 1);
8086 check_spends!(node_txn[0], remote_txn[0]);
8087 check_spends!(node_txn[3], remote_txn[0]);
8088 check_spends!(node_txn[4], remote_txn[0]);
8090 check_spends!(node_txn[1], chan.3); // local commitment
8091 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
8093 preimage = node_txn[0].txid();
8094 let index = node_txn[0].input[0].previous_output.vout;
8095 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8096 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8098 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
8099 (node_txn[3].clone(), node_txn[4].clone())
8101 (node_txn[4].clone(), node_txn[3].clone())
8104 preimage_bump = preimage_bump_tx;
8105 check_spends!(preimage_bump, remote_txn[0]);
8106 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
8108 timeout = timeout_tx.txid();
8109 let index = timeout_tx.input[0].previous_output.vout;
8110 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
8111 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
8115 assert_ne!(feerate_timeout, 0);
8116 assert_ne!(feerate_preimage, 0);
8118 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8119 connect_blocks(&nodes[1], 15);
8121 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8122 assert_eq!(node_txn.len(), 1);
8123 assert_eq!(node_txn[0].input.len(), 1);
8124 assert_eq!(preimage_bump.input.len(), 1);
8125 check_spends!(node_txn[0], remote_txn[0]);
8126 check_spends!(preimage_bump, remote_txn[0]);
8128 let index = preimage_bump.input[0].previous_output.vout;
8129 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8130 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8131 assert!(new_feerate * 100 > feerate_timeout * 125);
8132 assert_ne!(timeout, preimage_bump.txid());
8134 let index = node_txn[0].input[0].previous_output.vout;
8135 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8136 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8137 assert!(new_feerate * 100 > feerate_preimage * 125);
8138 assert_ne!(preimage, node_txn[0].txid());
8143 nodes[1].node.get_and_clear_pending_events();
8144 nodes[1].node.get_and_clear_pending_msg_events();
8148 fn test_counterparty_raa_skip_no_crash() {
8149 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8150 // commitment transaction, we would have happily carried on and provided them the next
8151 // commitment transaction based on one RAA forward. This would probably eventually have led to
8152 // channel closure, but it would not have resulted in funds loss. Still, our
8153 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8154 // check simply that the channel is closed in response to such an RAA, but don't check whether
8155 // we decide to punish our counterparty for revoking their funds (as we don't currently
8157 let chanmon_cfgs = create_chanmon_cfgs(2);
8158 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8159 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8160 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8161 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
8163 let per_commitment_secret;
8164 let next_per_commitment_point;
8166 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8167 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8169 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8171 // Make signer believe we got a counterparty signature, so that it allows the revocation
8172 keys.get_enforcement_state().last_holder_commitment -= 1;
8173 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8175 // Must revoke without gaps
8176 keys.get_enforcement_state().last_holder_commitment -= 1;
8177 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8179 keys.get_enforcement_state().last_holder_commitment -= 1;
8180 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8181 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8184 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8185 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8186 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8187 check_added_monitors!(nodes[1], 1);
8188 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8192 fn test_bump_txn_sanitize_tracking_maps() {
8193 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8194 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8196 let chanmon_cfgs = create_chanmon_cfgs(2);
8197 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8198 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8199 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8201 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8202 // Lock HTLC in both directions
8203 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8204 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8206 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8207 assert_eq!(revoked_local_txn[0].input.len(), 1);
8208 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8210 // Revoke local commitment tx
8211 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8213 // Broadcast set of revoked txn on A
8214 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8215 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8216 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8218 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8219 check_closed_broadcast!(nodes[0], true);
8220 check_added_monitors!(nodes[0], 1);
8221 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8223 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8224 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8225 check_spends!(node_txn[0], revoked_local_txn[0]);
8226 check_spends!(node_txn[1], revoked_local_txn[0]);
8227 check_spends!(node_txn[2], revoked_local_txn[0]);
8228 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8232 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8233 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8234 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8236 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8237 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8238 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8243 fn test_pending_claimed_htlc_no_balance_underflow() {
8244 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8245 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8246 let chanmon_cfgs = create_chanmon_cfgs(2);
8247 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8248 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8249 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8250 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8252 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8253 nodes[1].node.claim_funds(payment_preimage);
8254 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8255 check_added_monitors!(nodes[1], 1);
8256 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8258 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8259 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8260 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8261 check_added_monitors!(nodes[0], 1);
8262 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8264 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8265 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8266 // can get our balance.
8268 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8269 // the public key of the only hop. This works around ChannelDetails not showing the
8270 // almost-claimed HTLC as available balance.
8271 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8272 route.payment_params = None; // This is all wrong, but unnecessary
8273 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8274 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8275 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8277 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8281 fn test_channel_conf_timeout() {
8282 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8283 // confirm within 2016 blocks, as recommended by BOLT 2.
8284 let chanmon_cfgs = create_chanmon_cfgs(2);
8285 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8286 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8287 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8289 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());
8291 // The outbound node should wait forever for confirmation:
8292 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8293 // copied here instead of directly referencing the constant.
8294 connect_blocks(&nodes[0], 2016);
8295 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8297 // The inbound node should fail the channel after exactly 2016 blocks
8298 connect_blocks(&nodes[1], 2015);
8299 check_added_monitors!(nodes[1], 0);
8300 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8302 connect_blocks(&nodes[1], 1);
8303 check_added_monitors!(nodes[1], 1);
8304 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8305 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8306 assert_eq!(close_ev.len(), 1);
8308 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8309 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8310 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8312 _ => panic!("Unexpected event"),
8317 fn test_override_channel_config() {
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 // Node0 initiates a channel to node1 using the override config.
8324 let mut override_config = UserConfig::default();
8325 override_config.channel_handshake_config.our_to_self_delay = 200;
8327 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8329 // Assert the channel created by node0 is using the override config.
8330 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8331 assert_eq!(res.channel_flags, 0);
8332 assert_eq!(res.to_self_delay, 200);
8336 fn test_override_0msat_htlc_minimum() {
8337 let mut zero_config = UserConfig::default();
8338 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8339 let chanmon_cfgs = create_chanmon_cfgs(2);
8340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8342 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8344 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8345 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8346 assert_eq!(res.htlc_minimum_msat, 1);
8348 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8349 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8350 assert_eq!(res.htlc_minimum_msat, 1);
8354 fn test_channel_update_has_correct_htlc_maximum_msat() {
8355 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8356 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8357 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8358 // 90% of the `channel_value`.
8359 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8361 let mut config_30_percent = UserConfig::default();
8362 config_30_percent.channel_handshake_config.announced_channel = true;
8363 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8364 let mut config_50_percent = UserConfig::default();
8365 config_50_percent.channel_handshake_config.announced_channel = true;
8366 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8367 let mut config_95_percent = UserConfig::default();
8368 config_95_percent.channel_handshake_config.announced_channel = true;
8369 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8370 let mut config_100_percent = UserConfig::default();
8371 config_100_percent.channel_handshake_config.announced_channel = true;
8372 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8374 let chanmon_cfgs = create_chanmon_cfgs(4);
8375 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8376 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)]);
8377 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8379 let channel_value_satoshis = 100000;
8380 let channel_value_msat = channel_value_satoshis * 1000;
8381 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8382 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8383 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8385 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());
8386 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());
8388 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8389 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8390 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8391 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8392 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8393 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8395 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8396 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8398 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8399 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8400 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8402 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8406 fn test_manually_accept_inbound_channel_request() {
8407 let mut manually_accept_conf = UserConfig::default();
8408 manually_accept_conf.manually_accept_inbound_channels = true;
8409 let chanmon_cfgs = create_chanmon_cfgs(2);
8410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8412 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8414 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8415 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8417 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8419 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8420 // accepting the inbound channel request.
8421 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8423 let events = nodes[1].node.get_and_clear_pending_events();
8425 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8426 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8428 _ => panic!("Unexpected event"),
8431 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8432 assert_eq!(accept_msg_ev.len(), 1);
8434 match accept_msg_ev[0] {
8435 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8436 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8438 _ => panic!("Unexpected event"),
8441 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8443 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8444 assert_eq!(close_msg_ev.len(), 1);
8446 let events = nodes[1].node.get_and_clear_pending_events();
8448 Event::ChannelClosed { user_channel_id, .. } => {
8449 assert_eq!(user_channel_id, 23);
8451 _ => panic!("Unexpected event"),
8456 fn test_manually_reject_inbound_channel_request() {
8457 let mut manually_accept_conf = UserConfig::default();
8458 manually_accept_conf.manually_accept_inbound_channels = true;
8459 let chanmon_cfgs = create_chanmon_cfgs(2);
8460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8462 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8464 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8465 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8467 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8469 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8470 // rejecting the inbound channel request.
8471 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8473 let events = nodes[1].node.get_and_clear_pending_events();
8475 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8476 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8478 _ => panic!("Unexpected event"),
8481 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8482 assert_eq!(close_msg_ev.len(), 1);
8484 match close_msg_ev[0] {
8485 MessageSendEvent::HandleError { ref node_id, .. } => {
8486 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8488 _ => panic!("Unexpected event"),
8490 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8494 fn test_reject_funding_before_inbound_channel_accepted() {
8495 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8496 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8497 // the node operator before the counterparty sends a `FundingCreated` message. If a
8498 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8499 // and the channel should be closed.
8500 let mut manually_accept_conf = UserConfig::default();
8501 manually_accept_conf.manually_accept_inbound_channels = true;
8502 let chanmon_cfgs = create_chanmon_cfgs(2);
8503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8505 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8507 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8508 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8509 let temp_channel_id = res.temporary_channel_id;
8511 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8513 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8514 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8516 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8517 nodes[1].node.get_and_clear_pending_events();
8519 // Get the `AcceptChannel` message of `nodes[1]` without calling
8520 // `ChannelManager::accept_inbound_channel`, which generates a
8521 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8522 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8523 // succeed when `nodes[0]` is passed to it.
8524 let accept_chan_msg = {
8526 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8527 channel.get_accept_channel_message()
8529 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8531 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8533 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8534 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8536 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8537 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8539 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8540 assert_eq!(close_msg_ev.len(), 1);
8542 let expected_err = "FundingCreated message received before the channel was accepted";
8543 match close_msg_ev[0] {
8544 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8545 assert_eq!(msg.channel_id, temp_channel_id);
8546 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8547 assert_eq!(msg.data, expected_err);
8549 _ => panic!("Unexpected event"),
8552 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8556 fn test_can_not_accept_inbound_channel_twice() {
8557 let mut manually_accept_conf = UserConfig::default();
8558 manually_accept_conf.manually_accept_inbound_channels = true;
8559 let chanmon_cfgs = create_chanmon_cfgs(2);
8560 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8561 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8562 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8564 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8565 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8567 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8569 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8570 // accepting the inbound channel request.
8571 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8573 let events = nodes[1].node.get_and_clear_pending_events();
8575 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8576 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8577 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8579 Err(APIError::APIMisuseError { err }) => {
8580 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8582 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8583 Err(_) => panic!("Unexpected Error"),
8586 _ => panic!("Unexpected event"),
8589 // Ensure that the channel wasn't closed after attempting to accept it twice.
8590 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8591 assert_eq!(accept_msg_ev.len(), 1);
8593 match accept_msg_ev[0] {
8594 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8595 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8597 _ => panic!("Unexpected event"),
8602 fn test_can_not_accept_unknown_inbound_channel() {
8603 let chanmon_cfg = create_chanmon_cfgs(2);
8604 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8605 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8606 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8608 let unknown_channel_id = [0; 32];
8609 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8611 Err(APIError::ChannelUnavailable { err }) => {
8612 assert_eq!(err, "Can't accept a channel that doesn't exist");
8614 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8615 Err(_) => panic!("Unexpected Error"),
8620 fn test_simple_mpp() {
8621 // Simple test of sending a multi-path payment.
8622 let chanmon_cfgs = create_chanmon_cfgs(4);
8623 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8624 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8625 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8627 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;
8628 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;
8629 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;
8630 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;
8632 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8633 let path = route.paths[0].clone();
8634 route.paths.push(path);
8635 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8636 route.paths[0][0].short_channel_id = chan_1_id;
8637 route.paths[0][1].short_channel_id = chan_3_id;
8638 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8639 route.paths[1][0].short_channel_id = chan_2_id;
8640 route.paths[1][1].short_channel_id = chan_4_id;
8641 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8642 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8646 fn test_preimage_storage() {
8647 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8648 let chanmon_cfgs = create_chanmon_cfgs(2);
8649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8651 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8653 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8656 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8657 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8658 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8659 check_added_monitors!(nodes[0], 1);
8660 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8661 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8662 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8663 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8665 // Note that after leaving the above scope we have no knowledge of any arguments or return
8666 // values from previous calls.
8667 expect_pending_htlcs_forwardable!(nodes[1]);
8668 let events = nodes[1].node.get_and_clear_pending_events();
8669 assert_eq!(events.len(), 1);
8671 Event::PaymentReceived { ref purpose, .. } => {
8673 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8674 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8676 _ => panic!("expected PaymentPurpose::InvoicePayment")
8679 _ => panic!("Unexpected event"),
8684 #[allow(deprecated)]
8685 fn test_secret_timeout() {
8686 // Simple test of payment secret storage time outs. After
8687 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8688 let chanmon_cfgs = create_chanmon_cfgs(2);
8689 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8690 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8691 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8693 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8695 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8697 // We should fail to register the same payment hash twice, at least until we've connected a
8698 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8699 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8700 assert_eq!(err, "Duplicate payment hash");
8701 } else { panic!(); }
8703 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8705 header: BlockHeader {
8707 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8708 merkle_root: TxMerkleNode::all_zeros(),
8709 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8713 connect_block(&nodes[1], &block);
8714 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8715 assert_eq!(err, "Duplicate payment hash");
8716 } else { panic!(); }
8718 // If we then connect the second block, we should be able to register the same payment hash
8719 // again (this time getting a new payment secret).
8720 block.header.prev_blockhash = block.header.block_hash();
8721 block.header.time += 1;
8722 connect_block(&nodes[1], &block);
8723 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8724 assert_ne!(payment_secret_1, our_payment_secret);
8727 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8728 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8729 check_added_monitors!(nodes[0], 1);
8730 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8731 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8732 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8733 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8735 // Note that after leaving the above scope we have no knowledge of any arguments or return
8736 // values from previous calls.
8737 expect_pending_htlcs_forwardable!(nodes[1]);
8738 let events = nodes[1].node.get_and_clear_pending_events();
8739 assert_eq!(events.len(), 1);
8741 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8742 assert!(payment_preimage.is_none());
8743 assert_eq!(payment_secret, our_payment_secret);
8744 // We don't actually have the payment preimage with which to claim this payment!
8746 _ => panic!("Unexpected event"),
8751 fn test_bad_secret_hash() {
8752 // Simple test of unregistered payment hash/invalid payment secret handling
8753 let chanmon_cfgs = create_chanmon_cfgs(2);
8754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8756 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8758 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8760 let random_payment_hash = PaymentHash([42; 32]);
8761 let random_payment_secret = PaymentSecret([43; 32]);
8762 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8763 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8765 // All the below cases should end up being handled exactly identically, so we macro the
8766 // resulting events.
8767 macro_rules! handle_unknown_invalid_payment_data {
8768 ($payment_hash: expr) => {
8769 check_added_monitors!(nodes[0], 1);
8770 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8771 let payment_event = SendEvent::from_event(events.pop().unwrap());
8772 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8773 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8775 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8776 // again to process the pending backwards-failure of the HTLC
8777 expect_pending_htlcs_forwardable!(nodes[1]);
8778 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8779 check_added_monitors!(nodes[1], 1);
8781 // We should fail the payment back
8782 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8783 match events.pop().unwrap() {
8784 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8785 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8786 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8788 _ => panic!("Unexpected event"),
8793 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8794 // Error data is the HTLC value (100,000) and current block height
8795 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8797 // Send a payment with the right payment hash but the wrong payment secret
8798 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8799 handle_unknown_invalid_payment_data!(our_payment_hash);
8800 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8802 // Send a payment with a random payment hash, but the right payment secret
8803 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8804 handle_unknown_invalid_payment_data!(random_payment_hash);
8805 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8807 // Send a payment with a random payment hash and random payment secret
8808 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8809 handle_unknown_invalid_payment_data!(random_payment_hash);
8810 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8814 fn test_update_err_monitor_lockdown() {
8815 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8816 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8817 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8820 // This scenario may happen in a watchtower setup, where watchtower process a block height
8821 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8822 // commitment at same time.
8824 let chanmon_cfgs = create_chanmon_cfgs(2);
8825 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8826 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8827 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8829 // Create some initial channel
8830 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8831 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8833 // Rebalance the network to generate htlc in the two directions
8834 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8836 // Route a HTLC from node 0 to node 1 (but don't settle)
8837 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8839 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8840 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8841 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8842 let persister = test_utils::TestPersister::new();
8844 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8845 let mut w = test_utils::TestVecWriter(Vec::new());
8846 monitor.write(&mut w).unwrap();
8847 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8848 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8849 assert!(new_monitor == *monitor);
8850 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);
8851 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8854 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8855 let block = Block { header, txdata: vec![] };
8856 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8857 // transaction lock time requirements here.
8858 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8859 watchtower.chain_monitor.block_connected(&block, 200);
8861 // Try to update ChannelMonitor
8862 nodes[1].node.claim_funds(preimage);
8863 check_added_monitors!(nodes[1], 1);
8864 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8866 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8867 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8868 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8869 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8870 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8871 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8872 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8873 } else { assert!(false); }
8874 } else { assert!(false); };
8875 // Our local monitor is in-sync and hasn't processed yet timeout
8876 check_added_monitors!(nodes[0], 1);
8877 let events = nodes[0].node.get_and_clear_pending_events();
8878 assert_eq!(events.len(), 1);
8882 fn test_concurrent_monitor_claim() {
8883 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8884 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8885 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8886 // state N+1 confirms. Alice claims output from state N+1.
8888 let chanmon_cfgs = create_chanmon_cfgs(2);
8889 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8890 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8891 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8893 // Create some initial channel
8894 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8895 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8897 // Rebalance the network to generate htlc in the two directions
8898 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8900 // Route a HTLC from node 0 to node 1 (but don't settle)
8901 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8903 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8904 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8905 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8906 let persister = test_utils::TestPersister::new();
8907 let watchtower_alice = {
8908 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8909 let mut w = test_utils::TestVecWriter(Vec::new());
8910 monitor.write(&mut w).unwrap();
8911 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8912 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8913 assert!(new_monitor == *monitor);
8914 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);
8915 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8918 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8919 let block = Block { header, txdata: vec![] };
8920 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8921 // transaction lock time requirements here.
8922 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));
8923 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8925 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8927 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8928 assert_eq!(txn.len(), 2);
8932 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8933 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8934 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8935 let persister = test_utils::TestPersister::new();
8936 let watchtower_bob = {
8937 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8938 let mut w = test_utils::TestVecWriter(Vec::new());
8939 monitor.write(&mut w).unwrap();
8940 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8941 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8942 assert!(new_monitor == *monitor);
8943 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);
8944 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8947 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8948 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8950 // Route another payment to generate another update with still previous HTLC pending
8951 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8953 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8955 check_added_monitors!(nodes[1], 1);
8957 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8958 assert_eq!(updates.update_add_htlcs.len(), 1);
8959 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8960 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8961 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8962 // Watchtower Alice should already have seen the block and reject the update
8963 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8964 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8965 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8966 } else { assert!(false); }
8967 } else { assert!(false); };
8968 // Our local monitor is in-sync and hasn't processed yet timeout
8969 check_added_monitors!(nodes[0], 1);
8971 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8972 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8973 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8975 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8978 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8979 assert_eq!(txn.len(), 2);
8980 bob_state_y = txn[0].clone();
8984 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8985 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8986 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);
8988 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8989 assert_eq!(htlc_txn.len(), 1);
8990 check_spends!(htlc_txn[0], bob_state_y);
8995 fn test_pre_lockin_no_chan_closed_update() {
8996 // Test that if a peer closes a channel in response to a funding_created message we don't
8997 // generate a channel update (as the channel cannot appear on chain without a funding_signed
9000 // Doing so would imply a channel monitor update before the initial channel monitor
9001 // registration, violating our API guarantees.
9003 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
9004 // then opening a second channel with the same funding output as the first (which is not
9005 // rejected because the first channel does not exist in the ChannelManager) and closing it
9006 // before receiving funding_signed.
9007 let chanmon_cfgs = create_chanmon_cfgs(2);
9008 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9009 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9010 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9012 // Create an initial channel
9013 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9014 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9015 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9016 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9017 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
9019 // Move the first channel through the funding flow...
9020 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9022 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9023 check_added_monitors!(nodes[0], 0);
9025 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9026 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
9027 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
9028 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
9029 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
9033 fn test_htlc_no_detection() {
9034 // This test is a mutation to underscore the detection logic bug we had
9035 // before #653. HTLC value routed is above the remaining balance, thus
9036 // inverting HTLC and `to_remote` output. HTLC will come second and
9037 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9038 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9039 // outputs order detection for correct spending children filtring.
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 some initial channels
9047 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9049 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9050 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9051 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9052 assert_eq!(local_txn[0].input.len(), 1);
9053 assert_eq!(local_txn[0].output.len(), 3);
9054 check_spends!(local_txn[0], chan_1.3);
9056 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9057 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9058 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9059 // We deliberately connect the local tx twice as this should provoke a failure calling
9060 // this test before #653 fix.
9061 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);
9062 check_closed_broadcast!(nodes[0], true);
9063 check_added_monitors!(nodes[0], 1);
9064 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9065 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9067 let htlc_timeout = {
9068 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9069 assert_eq!(node_txn[1].input.len(), 1);
9070 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9071 check_spends!(node_txn[1], local_txn[0]);
9075 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9076 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9077 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9078 expect_payment_failed!(nodes[0], our_payment_hash, false);
9081 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9082 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9083 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9084 // Carol, Alice would be the upstream node, and Carol the downstream.)
9086 // Steps of the test:
9087 // 1) Alice sends a HTLC to Carol through Bob.
9088 // 2) Carol doesn't settle the HTLC.
9089 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9090 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9091 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9092 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9093 // 5) Carol release the preimage to Bob off-chain.
9094 // 6) Bob claims the offered output on the broadcasted commitment.
9095 let chanmon_cfgs = create_chanmon_cfgs(3);
9096 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9097 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9098 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9100 // Create some initial channels
9101 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9102 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9104 // Steps (1) and (2):
9105 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9106 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9108 // Check that Alice's commitment transaction now contains an output for this HTLC.
9109 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9110 check_spends!(alice_txn[0], chan_ab.3);
9111 assert_eq!(alice_txn[0].output.len(), 2);
9112 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9113 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9114 assert_eq!(alice_txn.len(), 2);
9116 // Steps (3) and (4):
9117 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9118 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9119 let mut force_closing_node = 0; // Alice force-closes
9120 let mut counterparty_node = 1; // Bob if Alice force-closes
9123 if !broadcast_alice {
9124 force_closing_node = 1;
9125 counterparty_node = 0;
9127 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9128 check_closed_broadcast!(nodes[force_closing_node], true);
9129 check_added_monitors!(nodes[force_closing_node], 1);
9130 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9131 if go_onchain_before_fulfill {
9132 let txn_to_broadcast = match broadcast_alice {
9133 true => alice_txn.clone(),
9134 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9136 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9137 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9138 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9139 if broadcast_alice {
9140 check_closed_broadcast!(nodes[1], true);
9141 check_added_monitors!(nodes[1], 1);
9142 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9144 assert_eq!(bob_txn.len(), 1);
9145 check_spends!(bob_txn[0], chan_ab.3);
9149 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9150 // process of removing the HTLC from their commitment transactions.
9151 nodes[2].node.claim_funds(payment_preimage);
9152 check_added_monitors!(nodes[2], 1);
9153 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9155 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9156 assert!(carol_updates.update_add_htlcs.is_empty());
9157 assert!(carol_updates.update_fail_htlcs.is_empty());
9158 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9159 assert!(carol_updates.update_fee.is_none());
9160 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9162 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9163 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9164 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9165 if !go_onchain_before_fulfill && broadcast_alice {
9166 let events = nodes[1].node.get_and_clear_pending_msg_events();
9167 assert_eq!(events.len(), 1);
9169 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9170 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9172 _ => panic!("Unexpected event"),
9175 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9176 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9177 // Carol<->Bob's updated commitment transaction info.
9178 check_added_monitors!(nodes[1], 2);
9180 let events = nodes[1].node.get_and_clear_pending_msg_events();
9181 assert_eq!(events.len(), 2);
9182 let bob_revocation = match events[0] {
9183 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9184 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9187 _ => panic!("Unexpected event"),
9189 let bob_updates = match events[1] {
9190 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9191 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9194 _ => panic!("Unexpected event"),
9197 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9198 check_added_monitors!(nodes[2], 1);
9199 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9200 check_added_monitors!(nodes[2], 1);
9202 let events = nodes[2].node.get_and_clear_pending_msg_events();
9203 assert_eq!(events.len(), 1);
9204 let carol_revocation = match events[0] {
9205 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9206 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9209 _ => panic!("Unexpected event"),
9211 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9212 check_added_monitors!(nodes[1], 1);
9214 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9215 // here's where we put said channel's commitment tx on-chain.
9216 let mut txn_to_broadcast = alice_txn.clone();
9217 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9218 if !go_onchain_before_fulfill {
9219 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9220 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9221 // If Bob was the one to force-close, he will have already passed these checks earlier.
9222 if broadcast_alice {
9223 check_closed_broadcast!(nodes[1], true);
9224 check_added_monitors!(nodes[1], 1);
9225 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9227 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9228 if broadcast_alice {
9229 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9230 // new block being connected. The ChannelManager being notified triggers a monitor update,
9231 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9232 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9234 assert_eq!(bob_txn.len(), 3);
9235 check_spends!(bob_txn[1], chan_ab.3);
9237 assert_eq!(bob_txn.len(), 2);
9238 check_spends!(bob_txn[0], chan_ab.3);
9243 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9244 // broadcasted commitment transaction.
9246 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9247 if go_onchain_before_fulfill {
9248 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9249 assert_eq!(bob_txn.len(), 2);
9251 let script_weight = match broadcast_alice {
9252 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9253 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9255 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9256 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9257 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9258 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9259 if broadcast_alice && !go_onchain_before_fulfill {
9260 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9261 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9263 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9264 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9270 fn test_onchain_htlc_settlement_after_close() {
9271 do_test_onchain_htlc_settlement_after_close(true, true);
9272 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9273 do_test_onchain_htlc_settlement_after_close(true, false);
9274 do_test_onchain_htlc_settlement_after_close(false, false);
9278 fn test_duplicate_chan_id() {
9279 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9280 // already open we reject it and keep the old channel.
9282 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9283 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9284 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9285 // updating logic for the existing channel.
9286 let chanmon_cfgs = create_chanmon_cfgs(2);
9287 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9288 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9289 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9291 // Create an initial channel
9292 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9293 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9294 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9295 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()));
9297 // Try to create a second channel with the same temporary_channel_id as the first and check
9298 // that it is rejected.
9299 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9301 let events = nodes[1].node.get_and_clear_pending_msg_events();
9302 assert_eq!(events.len(), 1);
9304 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9305 // Technically, at this point, nodes[1] would be justified in thinking both the
9306 // first (valid) and second (invalid) channels are closed, given they both have
9307 // the same non-temporary channel_id. However, currently we do not, so we just
9308 // move forward with it.
9309 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9310 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9312 _ => panic!("Unexpected event"),
9316 // Move the first channel through the funding flow...
9317 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9319 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9320 check_added_monitors!(nodes[0], 0);
9322 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9323 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9325 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9326 assert_eq!(added_monitors.len(), 1);
9327 assert_eq!(added_monitors[0].0, funding_output);
9328 added_monitors.clear();
9330 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9332 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9333 let channel_id = funding_outpoint.to_channel_id();
9335 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9338 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9339 // Technically this is allowed by the spec, but we don't support it and there's little reason
9340 // to. Still, it shouldn't cause any other issues.
9341 open_chan_msg.temporary_channel_id = channel_id;
9342 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9344 let events = nodes[1].node.get_and_clear_pending_msg_events();
9345 assert_eq!(events.len(), 1);
9347 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9348 // Technically, at this point, nodes[1] would be justified in thinking both
9349 // channels are closed, but currently we do not, so we just move forward with it.
9350 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9351 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9353 _ => panic!("Unexpected event"),
9357 // Now try to create a second channel which has a duplicate funding output.
9358 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9359 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9360 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
9361 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()));
9362 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9364 let funding_created = {
9365 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9366 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9367 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9368 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9369 // channelmanager in a possibly nonsense state instead).
9370 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9371 let logger = test_utils::TestLogger::new();
9372 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9374 check_added_monitors!(nodes[0], 0);
9375 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9376 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9377 // still needs to be cleared here.
9378 check_added_monitors!(nodes[1], 1);
9380 // ...still, nodes[1] will reject the duplicate channel.
9382 let events = nodes[1].node.get_and_clear_pending_msg_events();
9383 assert_eq!(events.len(), 1);
9385 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9386 // Technically, at this point, nodes[1] would be justified in thinking both
9387 // channels are closed, but currently we do not, so we just move forward with it.
9388 assert_eq!(msg.channel_id, channel_id);
9389 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9391 _ => panic!("Unexpected event"),
9395 // finally, finish creating the original channel and send a payment over it to make sure
9396 // everything is functional.
9397 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9399 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9400 assert_eq!(added_monitors.len(), 1);
9401 assert_eq!(added_monitors[0].0, funding_output);
9402 added_monitors.clear();
9405 let events_4 = nodes[0].node.get_and_clear_pending_events();
9406 assert_eq!(events_4.len(), 0);
9407 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9408 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9410 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9411 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9412 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9414 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9418 fn test_error_chans_closed() {
9419 // Test that we properly handle error messages, closing appropriate channels.
9421 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9422 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9423 // we can test various edge cases around it to ensure we don't regress.
9424 let chanmon_cfgs = create_chanmon_cfgs(3);
9425 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9426 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9427 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9429 // Create some initial channels
9430 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9431 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9432 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9434 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9435 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9436 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9438 // Closing a channel from a different peer has no effect
9439 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9440 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9442 // Closing one channel doesn't impact others
9443 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9444 check_added_monitors!(nodes[0], 1);
9445 check_closed_broadcast!(nodes[0], false);
9446 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9447 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9448 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9449 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);
9450 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);
9452 // A null channel ID should close all channels
9453 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9454 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9455 check_added_monitors!(nodes[0], 2);
9456 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9457 let events = nodes[0].node.get_and_clear_pending_msg_events();
9458 assert_eq!(events.len(), 2);
9460 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9461 assert_eq!(msg.contents.flags & 2, 2);
9463 _ => panic!("Unexpected event"),
9466 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9467 assert_eq!(msg.contents.flags & 2, 2);
9469 _ => panic!("Unexpected event"),
9471 // Note that at this point users of a standard PeerHandler will end up calling
9472 // peer_disconnected with no_connection_possible set to false, duplicating the
9473 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9474 // users with their own peer handling logic. We duplicate the call here, however.
9475 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9476 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9478 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9479 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9480 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9484 fn test_invalid_funding_tx() {
9485 // Test that we properly handle invalid funding transactions sent to us from a peer.
9487 // Previously, all other major lightning implementations had failed to properly sanitize
9488 // funding transactions from their counterparties, leading to a multi-implementation critical
9489 // security vulnerability (though we always sanitized properly, we've previously had
9490 // un-released crashes in the sanitization process).
9492 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9493 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9494 // gave up on it. We test this here by generating such a transaction.
9495 let chanmon_cfgs = create_chanmon_cfgs(2);
9496 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9497 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9498 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9500 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9501 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()));
9502 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()));
9504 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9506 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9507 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9508 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9510 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9511 let wit_program_script: Script = wit_program.into();
9512 for output in tx.output.iter_mut() {
9513 // Make the confirmed funding transaction have a bogus script_pubkey
9514 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9517 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9518 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()));
9519 check_added_monitors!(nodes[1], 1);
9521 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()));
9522 check_added_monitors!(nodes[0], 1);
9524 let events_1 = nodes[0].node.get_and_clear_pending_events();
9525 assert_eq!(events_1.len(), 0);
9527 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9528 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9529 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9531 let expected_err = "funding tx had wrong script/value or output index";
9532 confirm_transaction_at(&nodes[1], &tx, 1);
9533 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9534 check_added_monitors!(nodes[1], 1);
9535 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9536 assert_eq!(events_2.len(), 1);
9537 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9538 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9539 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9540 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9541 } else { panic!(); }
9542 } else { panic!(); }
9543 assert_eq!(nodes[1].node.list_channels().len(), 0);
9545 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9546 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9547 // as its not 32 bytes long.
9548 let mut spend_tx = Transaction {
9549 version: 2i32, lock_time: PackedLockTime::ZERO,
9550 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9551 previous_output: BitcoinOutPoint {
9555 script_sig: Script::new(),
9556 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9557 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9559 output: vec![TxOut {
9561 script_pubkey: Script::new(),
9564 check_spends!(spend_tx, tx);
9565 mine_transaction(&nodes[1], &spend_tx);
9568 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9569 // In the first version of the chain::Confirm interface, after a refactor was made to not
9570 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9571 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9572 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9573 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9574 // spending transaction until height N+1 (or greater). This was due to the way
9575 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9576 // spending transaction at the height the input transaction was confirmed at, not whether we
9577 // should broadcast a spending transaction at the current height.
9578 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9579 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9580 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9581 // until we learned about an additional block.
9583 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9584 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9585 let chanmon_cfgs = create_chanmon_cfgs(3);
9586 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9587 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9588 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9589 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9591 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9592 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9593 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9594 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9595 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9597 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9598 check_closed_broadcast!(nodes[1], true);
9599 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9600 check_added_monitors!(nodes[1], 1);
9601 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9602 assert_eq!(node_txn.len(), 1);
9604 let conf_height = nodes[1].best_block_info().1;
9605 if !test_height_before_timelock {
9606 connect_blocks(&nodes[1], 24 * 6);
9608 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9609 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9610 if test_height_before_timelock {
9611 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9612 // generate any events or broadcast any transactions
9613 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9614 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9616 // We should broadcast an HTLC transaction spending our funding transaction first
9617 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9618 assert_eq!(spending_txn.len(), 2);
9619 assert_eq!(spending_txn[0], node_txn[0]);
9620 check_spends!(spending_txn[1], node_txn[0]);
9621 // We should also generate a SpendableOutputs event with the to_self output (as its
9623 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9624 assert_eq!(descriptor_spend_txn.len(), 1);
9626 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9627 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9628 // additional block built on top of the current chain.
9629 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9630 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9631 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 }]);
9632 check_added_monitors!(nodes[1], 1);
9634 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9635 assert!(updates.update_add_htlcs.is_empty());
9636 assert!(updates.update_fulfill_htlcs.is_empty());
9637 assert_eq!(updates.update_fail_htlcs.len(), 1);
9638 assert!(updates.update_fail_malformed_htlcs.is_empty());
9639 assert!(updates.update_fee.is_none());
9640 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9641 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9642 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9647 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9648 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9649 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9653 fn test_forwardable_regen() {
9654 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9655 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9657 // We test it for both payment receipt and payment forwarding.
9659 let chanmon_cfgs = create_chanmon_cfgs(3);
9660 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9661 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9662 let persister: test_utils::TestPersister;
9663 let new_chain_monitor: test_utils::TestChainMonitor;
9664 let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9665 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9666 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9667 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9669 // First send a payment to nodes[1]
9670 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9671 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9672 check_added_monitors!(nodes[0], 1);
9674 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9675 assert_eq!(events.len(), 1);
9676 let payment_event = SendEvent::from_event(events.pop().unwrap());
9677 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9678 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9680 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9682 // Next send a payment which is forwarded by nodes[1]
9683 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9684 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9685 check_added_monitors!(nodes[0], 1);
9687 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9688 assert_eq!(events.len(), 1);
9689 let payment_event = SendEvent::from_event(events.pop().unwrap());
9690 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9691 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9693 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9695 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9697 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9698 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9699 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9701 let nodes_1_serialized = nodes[1].node.encode();
9702 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9703 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9704 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9705 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9707 persister = test_utils::TestPersister::new();
9708 let keys_manager = &chanmon_cfgs[1].keys_manager;
9709 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);
9710 nodes[1].chain_monitor = &new_chain_monitor;
9712 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9713 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9714 &mut chan_0_monitor_read, keys_manager).unwrap();
9715 assert!(chan_0_monitor_read.is_empty());
9716 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9717 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9718 &mut chan_1_monitor_read, keys_manager).unwrap();
9719 assert!(chan_1_monitor_read.is_empty());
9721 let mut nodes_1_read = &nodes_1_serialized[..];
9722 let (_, nodes_1_deserialized_tmp) = {
9723 let mut channel_monitors = HashMap::new();
9724 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9725 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9726 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9727 default_config: UserConfig::default(),
9729 fee_estimator: node_cfgs[1].fee_estimator,
9730 chain_monitor: nodes[1].chain_monitor,
9731 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9732 logger: nodes[1].logger,
9736 nodes_1_deserialized = nodes_1_deserialized_tmp;
9737 assert!(nodes_1_read.is_empty());
9739 assert_eq!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
9740 ChannelMonitorUpdateStatus::Completed);
9741 assert_eq!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor),
9742 ChannelMonitorUpdateStatus::Completed);
9743 nodes[1].node = &nodes_1_deserialized;
9744 check_added_monitors!(nodes[1], 2);
9746 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9747 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9748 // the commitment state.
9749 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9751 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9753 expect_pending_htlcs_forwardable!(nodes[1]);
9754 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9755 check_added_monitors!(nodes[1], 1);
9757 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9758 assert_eq!(events.len(), 1);
9759 let payment_event = SendEvent::from_event(events.pop().unwrap());
9760 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9761 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9762 expect_pending_htlcs_forwardable!(nodes[2]);
9763 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9765 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9766 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9769 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9770 let chanmon_cfgs = create_chanmon_cfgs(2);
9771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9773 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9775 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9777 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9778 .with_features(channelmanager::provided_invoice_features());
9779 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9781 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9784 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9785 check_added_monitors!(nodes[0], 1);
9786 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9787 assert_eq!(events.len(), 1);
9788 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9789 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9790 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9792 expect_pending_htlcs_forwardable!(nodes[1]);
9793 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9796 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9797 check_added_monitors!(nodes[0], 1);
9798 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9799 assert_eq!(events.len(), 1);
9800 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9801 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9802 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9803 // At this point, nodes[1] would notice it has too much value for the payment. It will
9804 // assume the second is a privacy attack (no longer particularly relevant
9805 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9806 // the first HTLC delivered above.
9809 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9810 nodes[1].node.process_pending_htlc_forwards();
9812 if test_for_second_fail_panic {
9813 // Now we go fail back the first HTLC from the user end.
9814 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9816 let expected_destinations = vec![
9817 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9818 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9820 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9821 nodes[1].node.process_pending_htlc_forwards();
9823 check_added_monitors!(nodes[1], 1);
9824 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9825 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9827 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9828 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9829 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9831 let failure_events = nodes[0].node.get_and_clear_pending_events();
9832 assert_eq!(failure_events.len(), 2);
9833 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9834 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9836 // Let the second HTLC fail and claim the first
9837 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9838 nodes[1].node.process_pending_htlc_forwards();
9840 check_added_monitors!(nodes[1], 1);
9841 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9842 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9843 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9845 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9847 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9852 fn test_dup_htlc_second_fail_panic() {
9853 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9854 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9855 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9856 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9857 do_test_dup_htlc_second_rejected(true);
9861 fn test_dup_htlc_second_rejected() {
9862 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9863 // simply reject the second HTLC but are still able to claim the first HTLC.
9864 do_test_dup_htlc_second_rejected(false);
9868 fn test_inconsistent_mpp_params() {
9869 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9870 // such HTLC and allow the second to stay.
9871 let chanmon_cfgs = create_chanmon_cfgs(4);
9872 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9873 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9874 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9876 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9877 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9878 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9879 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());
9881 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9882 .with_features(channelmanager::provided_invoice_features());
9883 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9884 assert_eq!(route.paths.len(), 2);
9885 route.paths.sort_by(|path_a, _| {
9886 // Sort the path so that the path through nodes[1] comes first
9887 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9888 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9890 let payment_params_opt = Some(payment_params);
9892 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9894 let cur_height = nodes[0].best_block_info().1;
9895 let payment_id = PaymentId([42; 32]);
9897 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();
9898 check_added_monitors!(nodes[0], 1);
9900 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9901 assert_eq!(events.len(), 1);
9902 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9904 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9907 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();
9908 check_added_monitors!(nodes[0], 1);
9910 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9911 assert_eq!(events.len(), 1);
9912 let payment_event = SendEvent::from_event(events.pop().unwrap());
9914 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9915 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9917 expect_pending_htlcs_forwardable!(nodes[2]);
9918 check_added_monitors!(nodes[2], 1);
9920 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9921 assert_eq!(events.len(), 1);
9922 let payment_event = SendEvent::from_event(events.pop().unwrap());
9924 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9925 check_added_monitors!(nodes[3], 0);
9926 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9928 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9929 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9930 // post-payment_secrets) and fail back the new HTLC.
9932 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9933 nodes[3].node.process_pending_htlc_forwards();
9934 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9935 nodes[3].node.process_pending_htlc_forwards();
9937 check_added_monitors!(nodes[3], 1);
9939 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9940 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9941 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9943 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 }]);
9944 check_added_monitors!(nodes[2], 1);
9946 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9947 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9948 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9950 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9952 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();
9953 check_added_monitors!(nodes[0], 1);
9955 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9956 assert_eq!(events.len(), 1);
9957 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9959 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9963 fn test_keysend_payments_to_public_node() {
9964 let chanmon_cfgs = create_chanmon_cfgs(2);
9965 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9966 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9967 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9969 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9970 let network_graph = nodes[0].network_graph;
9971 let payer_pubkey = nodes[0].node.get_our_node_id();
9972 let payee_pubkey = nodes[1].node.get_our_node_id();
9973 let route_params = RouteParameters {
9974 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9975 final_value_msat: 10000,
9976 final_cltv_expiry_delta: 40,
9978 let scorer = test_utils::TestScorer::with_penalty(0);
9979 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9980 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9982 let test_preimage = PaymentPreimage([42; 32]);
9983 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9984 check_added_monitors!(nodes[0], 1);
9985 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9986 assert_eq!(events.len(), 1);
9987 let event = events.pop().unwrap();
9988 let path = vec![&nodes[1]];
9989 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9990 claim_payment(&nodes[0], &path, test_preimage);
9994 fn test_keysend_payments_to_private_node() {
9995 let chanmon_cfgs = create_chanmon_cfgs(2);
9996 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9997 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9998 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10000 let payer_pubkey = nodes[0].node.get_our_node_id();
10001 let payee_pubkey = nodes[1].node.get_our_node_id();
10002 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10003 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10005 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
10006 let route_params = RouteParameters {
10007 payment_params: PaymentParameters::for_keysend(payee_pubkey),
10008 final_value_msat: 10000,
10009 final_cltv_expiry_delta: 40,
10011 let network_graph = nodes[0].network_graph;
10012 let first_hops = nodes[0].node.list_usable_channels();
10013 let scorer = test_utils::TestScorer::with_penalty(0);
10014 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10015 let route = find_route(
10016 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10017 nodes[0].logger, &scorer, &random_seed_bytes
10020 let test_preimage = PaymentPreimage([42; 32]);
10021 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
10022 check_added_monitors!(nodes[0], 1);
10023 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10024 assert_eq!(events.len(), 1);
10025 let event = events.pop().unwrap();
10026 let path = vec![&nodes[1]];
10027 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10028 claim_payment(&nodes[0], &path, test_preimage);
10032 fn test_double_partial_claim() {
10033 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
10034 // time out, the sender resends only some of the MPP parts, then the user processes the
10035 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10037 let chanmon_cfgs = create_chanmon_cfgs(4);
10038 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10039 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10040 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10042 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10043 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10044 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10045 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10047 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10048 assert_eq!(route.paths.len(), 2);
10049 route.paths.sort_by(|path_a, _| {
10050 // Sort the path so that the path through nodes[1] comes first
10051 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10052 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10055 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10056 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10057 // amount of time to respond to.
10059 // Connect some blocks to time out the payment
10060 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10061 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10063 let failed_destinations = vec![
10064 HTLCDestination::FailedPayment { payment_hash },
10065 HTLCDestination::FailedPayment { payment_hash },
10067 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10069 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10071 // nodes[1] now retries one of the two paths...
10072 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10073 check_added_monitors!(nodes[0], 2);
10075 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10076 assert_eq!(events.len(), 2);
10077 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10079 // At this point nodes[3] has received one half of the payment, and the user goes to handle
10080 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10081 nodes[3].node.claim_funds(payment_preimage);
10082 check_added_monitors!(nodes[3], 0);
10083 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10086 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10087 // Test what happens if a node receives an MPP payment, claims it, but crashes before
10088 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10089 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10090 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10091 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10092 // not have the preimage tied to the still-pending HTLC.
10094 // To get to the correct state, on startup we should propagate the preimage to the
10095 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10096 // receiving the preimage without a state update.
10098 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10099 // definitely claimed.
10100 let chanmon_cfgs = create_chanmon_cfgs(4);
10101 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10102 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10104 let persister: test_utils::TestPersister;
10105 let new_chain_monitor: test_utils::TestChainMonitor;
10106 let nodes_3_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10108 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10110 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10111 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10112 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;
10113 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;
10115 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10116 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10117 assert_eq!(route.paths.len(), 2);
10118 route.paths.sort_by(|path_a, _| {
10119 // Sort the path so that the path through nodes[1] comes first
10120 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10121 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10124 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10125 check_added_monitors!(nodes[0], 2);
10127 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10128 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10129 assert_eq!(send_events.len(), 2);
10130 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);
10131 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);
10133 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10134 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10135 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10136 if !persist_both_monitors {
10137 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10138 if outpoint.to_channel_id() == chan_id_not_persisted {
10139 assert!(original_monitor.0.is_empty());
10140 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10145 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10146 nodes[3].node.write(&mut original_manager).unwrap();
10148 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10150 nodes[3].node.claim_funds(payment_preimage);
10151 check_added_monitors!(nodes[3], 2);
10152 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10154 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10155 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10156 // with the old ChannelManager.
10157 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10158 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10159 if outpoint.to_channel_id() == chan_id_persisted {
10160 assert!(updated_monitor.0.is_empty());
10161 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10164 // If `persist_both_monitors` is set, get the second monitor here as well
10165 if persist_both_monitors {
10166 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10167 if outpoint.to_channel_id() == chan_id_not_persisted {
10168 assert!(original_monitor.0.is_empty());
10169 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10174 // Now restart nodes[3].
10175 persister = test_utils::TestPersister::new();
10176 let keys_manager = &chanmon_cfgs[3].keys_manager;
10177 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);
10178 nodes[3].chain_monitor = &new_chain_monitor;
10179 let mut monitors = Vec::new();
10180 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10181 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10182 monitors.push(deserialized_monitor);
10185 let config = UserConfig::default();
10186 nodes_3_deserialized = {
10187 let mut channel_monitors = HashMap::new();
10188 for monitor in monitors.iter_mut() {
10189 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10191 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10192 default_config: config,
10194 fee_estimator: node_cfgs[3].fee_estimator,
10195 chain_monitor: nodes[3].chain_monitor,
10196 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10197 logger: nodes[3].logger,
10201 nodes[3].node = &nodes_3_deserialized;
10203 for monitor in monitors {
10204 // On startup the preimage should have been copied into the non-persisted monitor:
10205 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10206 assert_eq!(nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor),
10207 ChannelMonitorUpdateStatus::Completed);
10209 check_added_monitors!(nodes[3], 2);
10211 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10212 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10214 // During deserialization, we should have closed one channel and broadcast its latest
10215 // commitment transaction. We should also still have the original PaymentReceived event we
10216 // never finished processing.
10217 let events = nodes[3].node.get_and_clear_pending_events();
10218 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10219 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10220 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10221 if persist_both_monitors {
10222 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10225 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10226 // ChannelManager prior to handling the original one.
10227 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10228 events[if persist_both_monitors { 3 } else { 2 }]
10230 assert_eq!(payment_hash, our_payment_hash);
10231 } else { panic!(); }
10233 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10234 if !persist_both_monitors {
10235 // If one of the two channels is still live, reveal the payment preimage over it.
10237 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10238 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10239 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10240 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10242 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10243 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10244 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10246 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10248 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10249 // claim should fly.
10250 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10251 check_added_monitors!(nodes[3], 1);
10252 assert_eq!(ds_msgs.len(), 2);
10253 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10255 let cs_updates = match ds_msgs[0] {
10256 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10257 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10258 check_added_monitors!(nodes[2], 1);
10259 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10260 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10261 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10267 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10268 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10269 expect_payment_sent!(nodes[0], payment_preimage);
10274 fn test_partial_claim_before_restart() {
10275 do_test_partial_claim_before_restart(false);
10276 do_test_partial_claim_before_restart(true);
10279 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10280 #[derive(Clone, Copy, PartialEq)]
10281 enum ExposureEvent {
10282 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10284 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10286 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10287 AtUpdateFeeOutbound,
10290 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10291 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10294 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10295 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10296 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10297 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10298 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10299 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10300 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10301 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10303 let chanmon_cfgs = create_chanmon_cfgs(2);
10304 let mut config = test_default_channel_config();
10305 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10306 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10307 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10308 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10310 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10311 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10312 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10313 open_channel.max_accepted_htlcs = 60;
10315 open_channel.dust_limit_satoshis = 546;
10317 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
10318 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10319 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
10321 let opt_anchors = false;
10323 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10326 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10327 chan.holder_dust_limit_satoshis = 546;
10331 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10332 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()));
10333 check_added_monitors!(nodes[1], 1);
10335 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()));
10336 check_added_monitors!(nodes[0], 1);
10338 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10339 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10340 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10342 let dust_buffer_feerate = {
10343 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10344 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10345 chan.get_dust_buffer_feerate(None) as u64
10347 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;
10348 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10350 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;
10351 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10353 let dust_htlc_on_counterparty_tx: u64 = 25;
10354 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10357 if dust_outbound_balance {
10358 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10359 // Outbound dust balance: 4372 sats
10360 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10361 for i in 0..dust_outbound_htlc_on_holder_tx {
10362 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10363 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10366 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10367 // Inbound dust balance: 4372 sats
10368 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10369 for _ in 0..dust_inbound_htlc_on_holder_tx {
10370 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10374 if dust_outbound_balance {
10375 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10376 // Outbound dust balance: 5000 sats
10377 for i in 0..dust_htlc_on_counterparty_tx {
10378 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10379 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10382 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10383 // Inbound dust balance: 5000 sats
10384 for _ in 0..dust_htlc_on_counterparty_tx {
10385 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10390 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10391 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10392 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 });
10393 let mut config = UserConfig::default();
10394 // With default dust exposure: 5000 sats
10396 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10397 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10398 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)));
10400 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)));
10402 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10403 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 });
10404 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10405 check_added_monitors!(nodes[1], 1);
10406 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10407 assert_eq!(events.len(), 1);
10408 let payment_event = SendEvent::from_event(events.remove(0));
10409 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10410 // With default dust exposure: 5000 sats
10412 // Outbound dust balance: 6399 sats
10413 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10414 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10415 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);
10417 // Outbound dust balance: 5200 sats
10418 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);
10420 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10421 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10422 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10424 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10425 *feerate_lock = *feerate_lock * 10;
10427 nodes[0].node.timer_tick_occurred();
10428 check_added_monitors!(nodes[0], 1);
10429 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);
10432 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10433 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10434 added_monitors.clear();
10438 fn test_max_dust_htlc_exposure() {
10439 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10440 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10441 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10442 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10443 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10444 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10445 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10446 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10447 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10448 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10449 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10450 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10454 fn test_non_final_funding_tx() {
10455 let chanmon_cfgs = create_chanmon_cfgs(2);
10456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10458 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10460 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10461 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10462 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
10463 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10464 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
10466 let best_height = nodes[0].node.best_block.read().unwrap().height();
10468 let chan_id = *nodes[0].network_chan_count.borrow();
10469 let events = nodes[0].node.get_and_clear_pending_events();
10470 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10471 assert_eq!(events.len(), 1);
10472 let mut tx = match events[0] {
10473 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10474 // Timelock the transaction _beyond_ the best client height + 2.
10475 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10476 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10479 _ => panic!("Unexpected event"),
10481 // Transaction should fail as it's evaluated as non-final for propagation.
10482 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10483 Err(APIError::APIMisuseError { err }) => {
10484 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10489 // However, transaction should be accepted if it's in a +2 headroom from best block.
10490 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10491 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10492 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());