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]);
564 fn test_sanity_on_in_flight_opens() {
565 do_test_sanity_on_in_flight_opens(0);
566 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
567 do_test_sanity_on_in_flight_opens(1);
568 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
569 do_test_sanity_on_in_flight_opens(2);
570 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
571 do_test_sanity_on_in_flight_opens(3);
572 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(4);
574 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(5);
576 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(6);
578 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(7);
580 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(8);
582 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
586 fn test_update_fee_vanilla() {
587 let chanmon_cfgs = create_chanmon_cfgs(2);
588 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
589 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
590 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
591 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
594 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
597 nodes[0].node.timer_tick_occurred();
598 check_added_monitors!(nodes[0], 1);
600 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
601 assert_eq!(events_0.len(), 1);
602 let (update_msg, commitment_signed) = match events_0[0] {
603 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 } } => {
604 (update_fee.as_ref(), commitment_signed)
606 _ => panic!("Unexpected event"),
608 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
610 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
611 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
612 check_added_monitors!(nodes[1], 1);
614 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
615 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
616 check_added_monitors!(nodes[0], 1);
618 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
619 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
620 // No commitment_signed so get_event_msg's assert(len == 1) passes
621 check_added_monitors!(nodes[0], 1);
623 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
624 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
625 check_added_monitors!(nodes[1], 1);
629 fn test_update_fee_that_funder_cannot_afford() {
630 let chanmon_cfgs = create_chanmon_cfgs(2);
631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
633 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
634 let channel_value = 5000;
636 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());
637 let channel_id = chan.2;
638 let secp_ctx = Secp256k1::new();
639 let default_config = UserConfig::default();
640 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
642 let opt_anchors = false;
644 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
645 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
646 // calculate two different feerates here - the expected local limit as well as the expected
648 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;
649 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
651 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
652 *feerate_lock = feerate;
654 nodes[0].node.timer_tick_occurred();
655 check_added_monitors!(nodes[0], 1);
656 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
658 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
660 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
662 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
664 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
666 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
667 assert_eq!(commitment_tx.output.len(), 2);
668 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
669 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
670 actual_fee = channel_value - actual_fee;
671 assert_eq!(total_fee, actual_fee);
675 // Increment the feerate by a small constant, accounting for rounding errors
676 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
679 nodes[0].node.timer_tick_occurred();
680 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
681 check_added_monitors!(nodes[0], 0);
683 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
685 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
686 // needed to sign the new commitment tx and (2) sign the new commitment tx.
687 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
688 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
689 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
690 let chan_signer = local_chan.get_signer();
691 let pubkeys = chan_signer.pubkeys();
692 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
693 pubkeys.funding_pubkey)
695 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
696 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
697 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
698 let chan_signer = remote_chan.get_signer();
699 let pubkeys = chan_signer.pubkeys();
700 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
701 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
702 pubkeys.funding_pubkey)
705 // Assemble the set of keys we can use for signatures for our commitment_signed message.
706 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
707 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
710 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
711 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
712 let local_chan_signer = local_chan.get_signer();
713 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
714 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
715 INITIAL_COMMITMENT_NUMBER - 1,
717 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
718 opt_anchors, local_funding, remote_funding,
719 commit_tx_keys.clone(),
720 non_buffer_feerate + 4,
722 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
724 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
727 let commit_signed_msg = msgs::CommitmentSigned {
730 htlc_signatures: res.1
733 let update_fee = msgs::UpdateFee {
735 feerate_per_kw: non_buffer_feerate + 4,
738 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
740 //While producing the commitment_signed response after handling a received update_fee request the
741 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
742 //Should produce and error.
743 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
744 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
745 check_added_monitors!(nodes[1], 1);
746 check_closed_broadcast!(nodes[1], true);
747 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
751 fn test_update_fee_with_fundee_update_add_htlc() {
752 let chanmon_cfgs = create_chanmon_cfgs(2);
753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
755 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
756 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
759 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
762 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
765 nodes[0].node.timer_tick_occurred();
766 check_added_monitors!(nodes[0], 1);
768 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
769 assert_eq!(events_0.len(), 1);
770 let (update_msg, commitment_signed) = match events_0[0] {
771 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 } } => {
772 (update_fee.as_ref(), commitment_signed)
774 _ => panic!("Unexpected event"),
776 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
777 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
778 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
779 check_added_monitors!(nodes[1], 1);
781 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
783 // nothing happens since node[1] is in AwaitingRemoteRevoke
784 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
786 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
787 assert_eq!(added_monitors.len(), 0);
788 added_monitors.clear();
790 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
791 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792 // node[1] has nothing to do
794 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
795 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
796 check_added_monitors!(nodes[0], 1);
798 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
799 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
800 // No commitment_signed so get_event_msg's assert(len == 1) passes
801 check_added_monitors!(nodes[0], 1);
802 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
803 check_added_monitors!(nodes[1], 1);
804 // AwaitingRemoteRevoke ends here
806 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
808 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
809 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
810 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
811 assert_eq!(commitment_update.update_fee.is_none(), true);
813 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
814 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
815 check_added_monitors!(nodes[0], 1);
816 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
818 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
819 check_added_monitors!(nodes[1], 1);
820 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
822 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
823 check_added_monitors!(nodes[1], 1);
824 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
825 // No commitment_signed so get_event_msg's assert(len == 1) passes
827 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
828 check_added_monitors!(nodes[0], 1);
829 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
831 expect_pending_htlcs_forwardable!(nodes[0]);
833 let events = nodes[0].node.get_and_clear_pending_events();
834 assert_eq!(events.len(), 1);
836 Event::PaymentReceived { .. } => { },
837 _ => panic!("Unexpected event"),
840 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
842 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
843 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
844 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
845 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
846 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
850 fn test_update_fee() {
851 let chanmon_cfgs = create_chanmon_cfgs(2);
852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
855 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
856 let channel_id = chan.2;
859 // (1) update_fee/commitment_signed ->
860 // <- (2) revoke_and_ack
861 // .- send (3) commitment_signed
862 // (4) update_fee/commitment_signed ->
863 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
864 // <- (3) commitment_signed delivered
865 // send (6) revoke_and_ack -.
866 // <- (5) deliver revoke_and_ack
867 // (6) deliver revoke_and_ack ->
868 // .- send (7) commitment_signed in response to (4)
869 // <- (7) deliver commitment_signed
872 // Create and deliver (1)...
875 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
876 feerate = *feerate_lock;
877 *feerate_lock = feerate + 20;
879 nodes[0].node.timer_tick_occurred();
880 check_added_monitors!(nodes[0], 1);
882 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
883 assert_eq!(events_0.len(), 1);
884 let (update_msg, commitment_signed) = match events_0[0] {
885 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 } } => {
886 (update_fee.as_ref(), commitment_signed)
888 _ => panic!("Unexpected event"),
890 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
892 // Generate (2) and (3):
893 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
894 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895 check_added_monitors!(nodes[1], 1);
898 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
899 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
900 check_added_monitors!(nodes[0], 1);
902 // Create and deliver (4)...
904 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905 *feerate_lock = feerate + 30;
907 nodes[0].node.timer_tick_occurred();
908 check_added_monitors!(nodes[0], 1);
909 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
910 assert_eq!(events_0.len(), 1);
911 let (update_msg, commitment_signed) = match events_0[0] {
912 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 } } => {
913 (update_fee.as_ref(), commitment_signed)
915 _ => panic!("Unexpected event"),
918 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
919 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
920 check_added_monitors!(nodes[1], 1);
922 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
923 // No commitment_signed so get_event_msg's assert(len == 1) passes
925 // Handle (3), creating (6):
926 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
927 check_added_monitors!(nodes[0], 1);
928 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
929 // No commitment_signed so get_event_msg's assert(len == 1) passes
932 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
933 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
934 check_added_monitors!(nodes[0], 1);
936 // Deliver (6), creating (7):
937 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
938 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
939 assert!(commitment_update.update_add_htlcs.is_empty());
940 assert!(commitment_update.update_fulfill_htlcs.is_empty());
941 assert!(commitment_update.update_fail_htlcs.is_empty());
942 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
943 assert!(commitment_update.update_fee.is_none());
944 check_added_monitors!(nodes[1], 1);
947 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
948 check_added_monitors!(nodes[0], 1);
949 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950 // No commitment_signed so get_event_msg's assert(len == 1) passes
952 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
953 check_added_monitors!(nodes[1], 1);
954 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
956 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
957 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
958 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
959 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
960 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
964 fn fake_network_test() {
965 // Simple test which builds a network of ChannelManagers, connects them to each other, and
966 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
967 let chanmon_cfgs = create_chanmon_cfgs(4);
968 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
969 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
970 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
972 // Create some initial channels
973 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
974 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
975 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
977 // Rebalance the network a bit by relaying one payment through all the channels...
978 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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);
983 // Send some more payments
984 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
985 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
986 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
988 // Test failure packets
989 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
990 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
992 // Add a new channel that skips 3
993 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
995 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
996 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
997 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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);
1003 // Do some rebalance loop payments, simultaneously
1004 let mut hops = Vec::with_capacity(3);
1005 hops.push(RouteHop {
1006 pubkey: nodes[2].node.get_our_node_id(),
1007 node_features: NodeFeatures::empty(),
1008 short_channel_id: chan_2.0.contents.short_channel_id,
1009 channel_features: ChannelFeatures::empty(),
1011 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1013 hops.push(RouteHop {
1014 pubkey: nodes[3].node.get_our_node_id(),
1015 node_features: NodeFeatures::empty(),
1016 short_channel_id: chan_3.0.contents.short_channel_id,
1017 channel_features: ChannelFeatures::empty(),
1019 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1021 hops.push(RouteHop {
1022 pubkey: nodes[1].node.get_our_node_id(),
1023 node_features: channelmanager::provided_node_features(),
1024 short_channel_id: chan_4.0.contents.short_channel_id,
1025 channel_features: channelmanager::provided_channel_features(),
1027 cltv_expiry_delta: TEST_FINAL_CLTV,
1029 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;
1030 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;
1031 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;
1033 let mut hops = Vec::with_capacity(3);
1034 hops.push(RouteHop {
1035 pubkey: nodes[3].node.get_our_node_id(),
1036 node_features: NodeFeatures::empty(),
1037 short_channel_id: chan_4.0.contents.short_channel_id,
1038 channel_features: ChannelFeatures::empty(),
1040 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1042 hops.push(RouteHop {
1043 pubkey: nodes[2].node.get_our_node_id(),
1044 node_features: NodeFeatures::empty(),
1045 short_channel_id: chan_3.0.contents.short_channel_id,
1046 channel_features: ChannelFeatures::empty(),
1048 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1050 hops.push(RouteHop {
1051 pubkey: nodes[1].node.get_our_node_id(),
1052 node_features: channelmanager::provided_node_features(),
1053 short_channel_id: chan_2.0.contents.short_channel_id,
1054 channel_features: channelmanager::provided_channel_features(),
1056 cltv_expiry_delta: TEST_FINAL_CLTV,
1058 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;
1059 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;
1060 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;
1062 // Claim the rebalances...
1063 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1064 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1066 // Close down the channels...
1067 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1068 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1069 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1070 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1071 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1072 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1073 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1074 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1075 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1076 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1077 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1078 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1082 fn holding_cell_htlc_counting() {
1083 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1084 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1085 // commitment dance rounds.
1086 let chanmon_cfgs = create_chanmon_cfgs(3);
1087 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1088 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1089 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1090 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1091 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1093 let mut payments = Vec::new();
1094 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1095 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1096 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1097 payments.push((payment_preimage, payment_hash));
1099 check_added_monitors!(nodes[1], 1);
1101 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1102 assert_eq!(events.len(), 1);
1103 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1104 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1106 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1107 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1109 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1112 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1113 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1114 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1117 // This should also be true if we try to forward a payment.
1118 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1120 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1121 check_added_monitors!(nodes[0], 1);
1124 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1125 assert_eq!(events.len(), 1);
1126 let payment_event = SendEvent::from_event(events.pop().unwrap());
1127 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1129 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1130 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1131 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1132 // fails), the second will process the resulting failure and fail the HTLC backward.
1133 expect_pending_htlcs_forwardable!(nodes[1]);
1134 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 }]);
1135 check_added_monitors!(nodes[1], 1);
1137 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1138 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1139 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1141 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1143 // Now forward all the pending HTLCs and claim them back
1144 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1145 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1146 check_added_monitors!(nodes[2], 1);
1148 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1149 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1150 check_added_monitors!(nodes[1], 1);
1151 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1153 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1154 check_added_monitors!(nodes[1], 1);
1155 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1157 for ref update in as_updates.update_add_htlcs.iter() {
1158 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1160 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1161 check_added_monitors!(nodes[2], 1);
1162 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1163 check_added_monitors!(nodes[2], 1);
1164 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1166 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1167 check_added_monitors!(nodes[1], 1);
1168 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1169 check_added_monitors!(nodes[1], 1);
1170 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1173 check_added_monitors!(nodes[2], 1);
1175 expect_pending_htlcs_forwardable!(nodes[2]);
1177 let events = nodes[2].node.get_and_clear_pending_events();
1178 assert_eq!(events.len(), payments.len());
1179 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1181 &Event::PaymentReceived { ref payment_hash, .. } => {
1182 assert_eq!(*payment_hash, *hash);
1184 _ => panic!("Unexpected event"),
1188 for (preimage, _) in payments.drain(..) {
1189 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1192 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1196 fn duplicate_htlc_test() {
1197 // Test that we accept duplicate payment_hash HTLCs across the network and that
1198 // claiming/failing them are all separate and don't affect each other
1199 let chanmon_cfgs = create_chanmon_cfgs(6);
1200 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1201 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1202 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1204 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1205 create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1206 create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1207 create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1208 create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1209 create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1211 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1213 *nodes[0].network_payment_count.borrow_mut() -= 1;
1214 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1216 *nodes[0].network_payment_count.borrow_mut() -= 1;
1217 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1219 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1220 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1221 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1225 fn test_duplicate_htlc_different_direction_onchain() {
1226 // Test that ChannelMonitor doesn't generate 2 preimage txn
1227 // when we have 2 HTLCs with same preimage that go across a node
1228 // in opposite directions, even with the same payment secret.
1229 let chanmon_cfgs = create_chanmon_cfgs(2);
1230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1232 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1234 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1237 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1239 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1241 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1242 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1243 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1245 // Provide preimage to node 0 by claiming payment
1246 nodes[0].node.claim_funds(payment_preimage);
1247 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1248 check_added_monitors!(nodes[0], 1);
1250 // Broadcast node 1 commitment txn
1251 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1253 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1254 let mut has_both_htlcs = 0; // check htlcs match ones committed
1255 for outp in remote_txn[0].output.iter() {
1256 if outp.value == 800_000 / 1000 {
1257 has_both_htlcs += 1;
1258 } else if outp.value == 900_000 / 1000 {
1259 has_both_htlcs += 1;
1262 assert_eq!(has_both_htlcs, 2);
1264 mine_transaction(&nodes[0], &remote_txn[0]);
1265 check_added_monitors!(nodes[0], 1);
1266 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1267 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1269 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1270 assert_eq!(claim_txn.len(), 5);
1272 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1273 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1274 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1276 check_spends!(claim_txn[3], remote_txn[0]);
1277 check_spends!(claim_txn[4], remote_txn[0]);
1278 let preimage_tx = &claim_txn[0];
1279 let (preimage_bump_tx, timeout_tx) = if claim_txn[3].input[0].previous_output == preimage_tx.input[0].previous_output {
1280 (&claim_txn[3], &claim_txn[4])
1282 (&claim_txn[4], &claim_txn[3])
1285 assert_eq!(preimage_tx.input.len(), 1);
1286 assert_eq!(preimage_bump_tx.input.len(), 1);
1288 assert_eq!(preimage_tx.input.len(), 1);
1289 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1290 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1292 assert_eq!(timeout_tx.input.len(), 1);
1293 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1294 check_spends!(timeout_tx, remote_txn[0]);
1295 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1297 let events = nodes[0].node.get_and_clear_pending_msg_events();
1298 assert_eq!(events.len(), 3);
1301 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1302 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1303 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1304 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1306 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, .. } } => {
1307 assert!(update_add_htlcs.is_empty());
1308 assert!(update_fail_htlcs.is_empty());
1309 assert_eq!(update_fulfill_htlcs.len(), 1);
1310 assert!(update_fail_malformed_htlcs.is_empty());
1311 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1313 _ => panic!("Unexpected event"),
1319 fn test_basic_channel_reserve() {
1320 let chanmon_cfgs = create_chanmon_cfgs(2);
1321 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1322 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1323 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1324 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1326 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1327 let channel_reserve = chan_stat.channel_reserve_msat;
1329 // The 2* and +1 are for the fee spike reserve.
1330 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1331 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1332 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1333 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1335 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1337 &APIError::ChannelUnavailable{ref err} =>
1338 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1339 _ => panic!("Unexpected error variant"),
1342 _ => panic!("Unexpected error variant"),
1344 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1345 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);
1347 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1351 fn test_fee_spike_violation_fails_htlc() {
1352 let chanmon_cfgs = create_chanmon_cfgs(2);
1353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1355 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1356 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1358 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1359 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1360 let secp_ctx = Secp256k1::new();
1361 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1363 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1365 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1366 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1367 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1368 let msg = msgs::UpdateAddHTLC {
1371 amount_msat: htlc_msat,
1372 payment_hash: payment_hash,
1373 cltv_expiry: htlc_cltv,
1374 onion_routing_packet: onion_packet,
1377 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1379 // Now manually create the commitment_signed message corresponding to the update_add
1380 // nodes[0] just sent. In the code for construction of this message, "local" refers
1381 // to the sender of the message, and "remote" refers to the receiver.
1383 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1385 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1387 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1388 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1389 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1390 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1391 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1392 let chan_signer = local_chan.get_signer();
1393 // Make the signer believe we validated another commitment, so we can release the secret
1394 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1396 let pubkeys = chan_signer.pubkeys();
1397 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1398 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1399 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1400 chan_signer.pubkeys().funding_pubkey)
1402 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1403 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1404 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1405 let chan_signer = remote_chan.get_signer();
1406 let pubkeys = chan_signer.pubkeys();
1407 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1408 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1409 chan_signer.pubkeys().funding_pubkey)
1412 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1413 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1414 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1416 // Build the remote commitment transaction so we can sign it, and then later use the
1417 // signature for the commitment_signed message.
1418 let local_chan_balance = 1313;
1420 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1422 amount_msat: 3460001,
1423 cltv_expiry: htlc_cltv,
1425 transaction_output_index: Some(1),
1428 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1431 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1432 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1433 let local_chan_signer = local_chan.get_signer();
1434 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1438 local_chan.opt_anchors(), local_funding, remote_funding,
1439 commit_tx_keys.clone(),
1441 &mut vec![(accepted_htlc_info, ())],
1442 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1444 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1447 let commit_signed_msg = msgs::CommitmentSigned {
1450 htlc_signatures: res.1
1453 // Send the commitment_signed message to the nodes[1].
1454 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1455 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1457 // Send the RAA to nodes[1].
1458 let raa_msg = msgs::RevokeAndACK {
1460 per_commitment_secret: local_secret,
1461 next_per_commitment_point: next_local_point
1463 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1465 let events = nodes[1].node.get_and_clear_pending_msg_events();
1466 assert_eq!(events.len(), 1);
1467 // Make sure the HTLC failed in the way we expect.
1469 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1470 assert_eq!(update_fail_htlcs.len(), 1);
1471 update_fail_htlcs[0].clone()
1473 _ => panic!("Unexpected event"),
1475 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1476 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1478 check_added_monitors!(nodes[1], 2);
1482 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1483 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1484 // Set the fee rate for the channel very high, to the point where the fundee
1485 // sending any above-dust amount would result in a channel reserve violation.
1486 // In this test we check that we would be prevented from sending an HTLC in
1488 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1489 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1490 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1491 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1492 let default_config = UserConfig::default();
1493 let opt_anchors = false;
1495 let mut push_amt = 100_000_000;
1496 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1498 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1500 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1502 // Sending exactly enough to hit the reserve amount should be accepted
1503 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1504 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1507 // However one more HTLC should be significantly over the reserve amount and fail.
1508 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1509 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1510 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1511 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1512 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);
1516 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1517 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1518 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1519 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1520 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1521 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1522 let default_config = UserConfig::default();
1523 let opt_anchors = false;
1525 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1526 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1527 // transaction fee with 0 HTLCs (183 sats)).
1528 let mut push_amt = 100_000_000;
1529 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1530 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1531 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1533 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1534 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1535 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1538 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1539 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1540 let secp_ctx = Secp256k1::new();
1541 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1542 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1543 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1544 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1545 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1546 let msg = msgs::UpdateAddHTLC {
1548 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1549 amount_msat: htlc_msat,
1550 payment_hash: payment_hash,
1551 cltv_expiry: htlc_cltv,
1552 onion_routing_packet: onion_packet,
1555 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1556 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1557 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);
1558 assert_eq!(nodes[0].node.list_channels().len(), 0);
1559 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1560 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1561 check_added_monitors!(nodes[0], 1);
1562 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() });
1566 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1567 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1568 // calculating our commitment transaction fee (this was previously broken).
1569 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1570 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1574 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1575 let default_config = UserConfig::default();
1576 let opt_anchors = false;
1578 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1579 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1580 // transaction fee with 0 HTLCs (183 sats)).
1581 let mut push_amt = 100_000_000;
1582 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1583 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1584 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1586 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1587 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1588 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1589 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1590 // commitment transaction fee.
1591 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1593 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1594 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1595 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1598 // One more than the dust amt should fail, however.
1599 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1600 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1601 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1605 fn test_chan_init_feerate_unaffordability() {
1606 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1607 // channel reserve and feerate requirements.
1608 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1609 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1612 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1613 let default_config = UserConfig::default();
1614 let opt_anchors = false;
1616 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1618 let mut push_amt = 100_000_000;
1619 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1620 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1621 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1623 // During open, we don't have a "counterparty channel reserve" to check against, so that
1624 // requirement only comes into play on the open_channel handling side.
1625 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1626 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1627 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1628 open_channel_msg.push_msat += 1;
1629 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1631 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1632 assert_eq!(msg_events.len(), 1);
1633 match msg_events[0] {
1634 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1635 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1637 _ => panic!("Unexpected event"),
1642 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1643 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1644 // calculating our counterparty's commitment transaction fee (this was previously broken).
1645 let chanmon_cfgs = create_chanmon_cfgs(2);
1646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1648 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1649 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1651 let payment_amt = 46000; // Dust amount
1652 // In the previous code, these first four payments would succeed.
1653 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
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);
1658 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1659 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1660 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1666 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1667 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1668 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1673 let chanmon_cfgs = create_chanmon_cfgs(3);
1674 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1675 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1676 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1677 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1678 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1681 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1682 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1683 let feerate = get_feerate!(nodes[0], chan.2);
1684 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1686 // Add a 2* and +1 for the fee spike reserve.
1687 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1688 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;
1689 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1691 // Add a pending HTLC.
1692 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1693 let payment_event_1 = {
1694 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1695 check_added_monitors!(nodes[0], 1);
1697 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1698 assert_eq!(events.len(), 1);
1699 SendEvent::from_event(events.remove(0))
1701 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1703 // Attempt to trigger a channel reserve violation --> payment failure.
1704 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1705 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;
1706 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1707 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1709 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1710 let secp_ctx = Secp256k1::new();
1711 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1712 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1713 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1714 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1715 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1716 let msg = msgs::UpdateAddHTLC {
1719 amount_msat: htlc_msat + 1,
1720 payment_hash: our_payment_hash_1,
1721 cltv_expiry: htlc_cltv,
1722 onion_routing_packet: onion_packet,
1725 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1726 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1727 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1728 assert_eq!(nodes[1].node.list_channels().len(), 1);
1729 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1730 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1731 check_added_monitors!(nodes[1], 1);
1732 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1736 fn test_inbound_outbound_capacity_is_not_zero() {
1737 let chanmon_cfgs = create_chanmon_cfgs(2);
1738 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1739 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1740 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1741 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1742 let channels0 = node_chanmgrs[0].list_channels();
1743 let channels1 = node_chanmgrs[1].list_channels();
1744 let default_config = UserConfig::default();
1745 assert_eq!(channels0.len(), 1);
1746 assert_eq!(channels1.len(), 1);
1748 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1749 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1750 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1752 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1753 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1756 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1757 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1761 fn test_channel_reserve_holding_cell_htlcs() {
1762 let chanmon_cfgs = create_chanmon_cfgs(3);
1763 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1764 // When this test was written, the default base fee floated based on the HTLC count.
1765 // It is now fixed, so we simply set the fee to the expected value here.
1766 let mut config = test_default_channel_config();
1767 config.channel_config.forwarding_fee_base_msat = 239;
1768 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1769 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1770 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1771 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1773 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1774 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1776 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1777 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1779 macro_rules! expect_forward {
1781 let mut events = $node.node.get_and_clear_pending_msg_events();
1782 assert_eq!(events.len(), 1);
1783 check_added_monitors!($node, 1);
1784 let payment_event = SendEvent::from_event(events.remove(0));
1789 let feemsat = 239; // set above
1790 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1791 let feerate = get_feerate!(nodes[0], chan_1.2);
1792 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1794 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1796 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1798 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1799 .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1800 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);
1801 route.paths[0].last_mut().unwrap().fee_msat += 1;
1802 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1804 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1805 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)));
1806 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1807 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);
1810 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1811 // nodes[0]'s wealth
1813 let amt_msat = recv_value_0 + total_fee_msat;
1814 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1815 // Also, ensure that each payment has enough to be over the dust limit to
1816 // ensure it'll be included in each commit tx fee calculation.
1817 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1818 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1819 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1823 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1824 .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1825 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1826 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1827 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1829 let (stat01_, stat11_, stat12_, stat22_) = (
1830 get_channel_value_stat!(nodes[0], chan_1.2),
1831 get_channel_value_stat!(nodes[1], chan_1.2),
1832 get_channel_value_stat!(nodes[1], chan_2.2),
1833 get_channel_value_stat!(nodes[2], chan_2.2),
1836 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1837 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1838 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1839 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1840 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1843 // adding pending output.
1844 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1845 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1846 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1847 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1848 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1849 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1850 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1851 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1852 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1854 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1855 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1856 let amt_msat_1 = recv_value_1 + total_fee_msat;
1858 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);
1859 let payment_event_1 = {
1860 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1861 check_added_monitors!(nodes[0], 1);
1863 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1864 assert_eq!(events.len(), 1);
1865 SendEvent::from_event(events.remove(0))
1867 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1869 // channel reserve test with htlc pending output > 0
1870 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1872 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1873 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1874 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1875 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1878 // split the rest to test holding cell
1879 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1880 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1881 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1882 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1884 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1885 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);
1888 // now see if they go through on both sides
1889 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);
1890 // but this will stuck in the holding cell
1891 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1892 check_added_monitors!(nodes[0], 0);
1893 let events = nodes[0].node.get_and_clear_pending_events();
1894 assert_eq!(events.len(), 0);
1896 // test with outbound holding cell amount > 0
1898 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1899 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1900 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1901 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1902 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);
1905 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);
1906 // this will also stuck in the holding cell
1907 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1908 check_added_monitors!(nodes[0], 0);
1909 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1910 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1912 // flush the pending htlc
1913 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1914 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1915 check_added_monitors!(nodes[1], 1);
1917 // the pending htlc should be promoted to committed
1918 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1919 check_added_monitors!(nodes[0], 1);
1920 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1922 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1923 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1924 // No commitment_signed so get_event_msg's assert(len == 1) passes
1925 check_added_monitors!(nodes[0], 1);
1927 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1928 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1929 check_added_monitors!(nodes[1], 1);
1931 expect_pending_htlcs_forwardable!(nodes[1]);
1933 let ref payment_event_11 = expect_forward!(nodes[1]);
1934 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1935 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1937 expect_pending_htlcs_forwardable!(nodes[2]);
1938 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1940 // flush the htlcs in the holding cell
1941 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1942 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1943 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1944 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1945 expect_pending_htlcs_forwardable!(nodes[1]);
1947 let ref payment_event_3 = expect_forward!(nodes[1]);
1948 assert_eq!(payment_event_3.msgs.len(), 2);
1949 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1950 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1952 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1953 expect_pending_htlcs_forwardable!(nodes[2]);
1955 let events = nodes[2].node.get_and_clear_pending_events();
1956 assert_eq!(events.len(), 2);
1958 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1959 assert_eq!(our_payment_hash_21, *payment_hash);
1960 assert_eq!(recv_value_21, amount_msat);
1962 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1963 assert!(payment_preimage.is_none());
1964 assert_eq!(our_payment_secret_21, *payment_secret);
1966 _ => panic!("expected PaymentPurpose::InvoicePayment")
1969 _ => panic!("Unexpected event"),
1972 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1973 assert_eq!(our_payment_hash_22, *payment_hash);
1974 assert_eq!(recv_value_22, amount_msat);
1976 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1977 assert!(payment_preimage.is_none());
1978 assert_eq!(our_payment_secret_22, *payment_secret);
1980 _ => panic!("expected PaymentPurpose::InvoicePayment")
1983 _ => panic!("Unexpected event"),
1986 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1987 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1988 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1990 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1991 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1992 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1994 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1995 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);
1996 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1997 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1998 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2000 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2001 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2005 fn channel_reserve_in_flight_removes() {
2006 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2007 // can send to its counterparty, but due to update ordering, the other side may not yet have
2008 // considered those HTLCs fully removed.
2009 // This tests that we don't count HTLCs which will not be included in the next remote
2010 // commitment transaction towards the reserve value (as it implies no commitment transaction
2011 // will be generated which violates the remote reserve value).
2012 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2014 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2015 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2016 // you only consider the value of the first HTLC, it may not),
2017 // * start routing a third HTLC from A to B,
2018 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2019 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2020 // * deliver the first fulfill from B
2021 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2023 // * deliver A's response CS and RAA.
2024 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2025 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2026 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2027 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2028 let chanmon_cfgs = create_chanmon_cfgs(2);
2029 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2030 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2031 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2032 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2034 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2035 // Route the first two HTLCs.
2036 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2037 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2038 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2040 // Start routing the third HTLC (this is just used to get everyone in the right state).
2041 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2043 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2044 check_added_monitors!(nodes[0], 1);
2045 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2046 assert_eq!(events.len(), 1);
2047 SendEvent::from_event(events.remove(0))
2050 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2051 // initial fulfill/CS.
2052 nodes[1].node.claim_funds(payment_preimage_1);
2053 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2054 check_added_monitors!(nodes[1], 1);
2055 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2057 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2058 // remove the second HTLC when we send the HTLC back from B to A.
2059 nodes[1].node.claim_funds(payment_preimage_2);
2060 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2061 check_added_monitors!(nodes[1], 1);
2062 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2064 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2065 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2066 check_added_monitors!(nodes[0], 1);
2067 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2068 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2070 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2071 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2072 check_added_monitors!(nodes[1], 1);
2073 // B is already AwaitingRAA, so cant generate a CS here
2074 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2076 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2077 check_added_monitors!(nodes[1], 1);
2078 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2080 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2081 check_added_monitors!(nodes[0], 1);
2082 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2084 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2085 check_added_monitors!(nodes[1], 1);
2086 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2088 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2089 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2090 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2091 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2092 // on-chain as necessary).
2093 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2094 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2095 check_added_monitors!(nodes[0], 1);
2096 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2097 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2099 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2100 check_added_monitors!(nodes[1], 1);
2101 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2103 expect_pending_htlcs_forwardable!(nodes[1]);
2104 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2106 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2107 // resolve the second HTLC from A's point of view.
2108 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2109 check_added_monitors!(nodes[0], 1);
2110 expect_payment_path_successful!(nodes[0]);
2111 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2113 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2114 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2115 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2117 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2118 check_added_monitors!(nodes[1], 1);
2119 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2120 assert_eq!(events.len(), 1);
2121 SendEvent::from_event(events.remove(0))
2124 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2125 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2126 check_added_monitors!(nodes[0], 1);
2127 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2129 // Now just resolve all the outstanding messages/HTLCs for completeness...
2131 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2132 check_added_monitors!(nodes[1], 1);
2133 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2135 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2136 check_added_monitors!(nodes[1], 1);
2138 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2139 check_added_monitors!(nodes[0], 1);
2140 expect_payment_path_successful!(nodes[0]);
2141 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2143 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144 check_added_monitors!(nodes[1], 1);
2145 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2147 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2148 check_added_monitors!(nodes[0], 1);
2150 expect_pending_htlcs_forwardable!(nodes[0]);
2151 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2153 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2154 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2158 fn channel_monitor_network_test() {
2159 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2160 // tests that ChannelMonitor is able to recover from various states.
2161 let chanmon_cfgs = create_chanmon_cfgs(5);
2162 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2163 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2164 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2166 // Create some initial channels
2167 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2168 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2169 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2170 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2172 // Make sure all nodes are at the same starting height
2173 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2174 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2175 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2176 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2177 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2179 // Rebalance the network a bit by relaying one payment through all the channels...
2180 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
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);
2185 // Simple case with no pending HTLCs:
2186 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2187 check_added_monitors!(nodes[1], 1);
2188 check_closed_broadcast!(nodes[1], true);
2190 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2191 assert_eq!(node_txn.len(), 1);
2192 mine_transaction(&nodes[0], &node_txn[0]);
2193 check_added_monitors!(nodes[0], 1);
2194 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2196 check_closed_broadcast!(nodes[0], true);
2197 assert_eq!(nodes[0].node.list_channels().len(), 0);
2198 assert_eq!(nodes[1].node.list_channels().len(), 1);
2199 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2200 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2202 // One pending HTLC is discarded by the force-close:
2203 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2205 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2206 // broadcasted until we reach the timelock time).
2207 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2208 check_closed_broadcast!(nodes[1], true);
2209 check_added_monitors!(nodes[1], 1);
2211 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2212 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2213 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2214 mine_transaction(&nodes[2], &node_txn[0]);
2215 check_added_monitors!(nodes[2], 1);
2216 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2218 check_closed_broadcast!(nodes[2], true);
2219 assert_eq!(nodes[1].node.list_channels().len(), 0);
2220 assert_eq!(nodes[2].node.list_channels().len(), 1);
2221 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2222 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2224 macro_rules! claim_funds {
2225 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2227 $node.node.claim_funds($preimage);
2228 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2229 check_added_monitors!($node, 1);
2231 let events = $node.node.get_and_clear_pending_msg_events();
2232 assert_eq!(events.len(), 1);
2234 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2235 assert!(update_add_htlcs.is_empty());
2236 assert!(update_fail_htlcs.is_empty());
2237 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2239 _ => panic!("Unexpected event"),
2245 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2246 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2247 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2248 check_added_monitors!(nodes[2], 1);
2249 check_closed_broadcast!(nodes[2], true);
2250 let node2_commitment_txid;
2252 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2253 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2254 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2255 node2_commitment_txid = node_txn[0].txid();
2257 // Claim the payment on nodes[3], giving it knowledge of the preimage
2258 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2259 mine_transaction(&nodes[3], &node_txn[0]);
2260 check_added_monitors!(nodes[3], 1);
2261 check_preimage_claim(&nodes[3], &node_txn);
2263 check_closed_broadcast!(nodes[3], true);
2264 assert_eq!(nodes[2].node.list_channels().len(), 0);
2265 assert_eq!(nodes[3].node.list_channels().len(), 1);
2266 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2267 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2269 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2270 // confusing us in the following tests.
2271 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2273 // One pending HTLC to time out:
2274 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2275 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2278 let (close_chan_update_1, close_chan_update_2) = {
2279 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2280 let events = nodes[3].node.get_and_clear_pending_msg_events();
2281 assert_eq!(events.len(), 2);
2282 let close_chan_update_1 = match events[0] {
2283 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2286 _ => panic!("Unexpected event"),
2289 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2290 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2292 _ => panic!("Unexpected event"),
2294 check_added_monitors!(nodes[3], 1);
2296 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2298 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2299 node_txn.retain(|tx| {
2300 if tx.input[0].previous_output.txid == node2_commitment_txid {
2306 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2308 // Claim the payment on nodes[4], giving it knowledge of the preimage
2309 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2311 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2312 let events = nodes[4].node.get_and_clear_pending_msg_events();
2313 assert_eq!(events.len(), 2);
2314 let close_chan_update_2 = match events[0] {
2315 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2318 _ => panic!("Unexpected event"),
2321 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2322 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2324 _ => panic!("Unexpected event"),
2326 check_added_monitors!(nodes[4], 1);
2327 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2329 mine_transaction(&nodes[4], &node_txn[0]);
2330 check_preimage_claim(&nodes[4], &node_txn);
2331 (close_chan_update_1, close_chan_update_2)
2333 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2334 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2335 assert_eq!(nodes[3].node.list_channels().len(), 0);
2336 assert_eq!(nodes[4].node.list_channels().len(), 0);
2338 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2339 ChannelMonitorUpdateStatus::Completed);
2340 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2341 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2345 fn test_justice_tx() {
2346 // Test justice txn built on revoked HTLC-Success tx, against both sides
2347 let mut alice_config = UserConfig::default();
2348 alice_config.channel_handshake_config.announced_channel = true;
2349 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2350 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2351 let mut bob_config = UserConfig::default();
2352 bob_config.channel_handshake_config.announced_channel = true;
2353 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2354 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2355 let user_cfgs = [Some(alice_config), Some(bob_config)];
2356 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2357 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2358 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2359 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2360 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2361 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2362 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2363 // Create some new channels:
2364 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2366 // A pending HTLC which will be revoked:
2367 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2368 // Get the will-be-revoked local txn from nodes[0]
2369 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2370 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2371 assert_eq!(revoked_local_txn[0].input.len(), 1);
2372 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2373 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2374 assert_eq!(revoked_local_txn[1].input.len(), 1);
2375 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2376 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2377 // Revoke the old state
2378 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2381 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2383 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2384 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2385 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2387 check_spends!(node_txn[0], revoked_local_txn[0]);
2388 node_txn.swap_remove(0);
2389 node_txn.truncate(1);
2391 check_added_monitors!(nodes[1], 1);
2392 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2393 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2395 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2396 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2397 // Verify broadcast of revoked HTLC-timeout
2398 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2399 check_added_monitors!(nodes[0], 1);
2400 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2401 // Broadcast revoked HTLC-timeout on node 1
2402 mine_transaction(&nodes[1], &node_txn[1]);
2403 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2405 get_announce_close_broadcast_events(&nodes, 0, 1);
2407 assert_eq!(nodes[0].node.list_channels().len(), 0);
2408 assert_eq!(nodes[1].node.list_channels().len(), 0);
2410 // We test justice_tx build by A on B's revoked HTLC-Success tx
2411 // Create some new channels:
2412 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2414 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2418 // A pending HTLC which will be revoked:
2419 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2420 // Get the will-be-revoked local txn from B
2421 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2422 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2423 assert_eq!(revoked_local_txn[0].input.len(), 1);
2424 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2425 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2426 // Revoke the old state
2427 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2429 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2431 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2432 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2433 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2435 check_spends!(node_txn[0], revoked_local_txn[0]);
2436 node_txn.swap_remove(0);
2438 check_added_monitors!(nodes[0], 1);
2439 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2441 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2442 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2443 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2444 check_added_monitors!(nodes[1], 1);
2445 mine_transaction(&nodes[0], &node_txn[1]);
2446 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2447 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2449 get_announce_close_broadcast_events(&nodes, 0, 1);
2450 assert_eq!(nodes[0].node.list_channels().len(), 0);
2451 assert_eq!(nodes[1].node.list_channels().len(), 0);
2455 fn revoked_output_claim() {
2456 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2457 // transaction is broadcast by its counterparty
2458 let chanmon_cfgs = create_chanmon_cfgs(2);
2459 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2460 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2461 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2462 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2463 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2464 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2465 assert_eq!(revoked_local_txn.len(), 1);
2466 // Only output is the full channel value back to nodes[0]:
2467 assert_eq!(revoked_local_txn[0].output.len(), 1);
2468 // Send a payment through, updating everyone's latest commitment txn
2469 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2471 // Inform nodes[1] that nodes[0] broadcast a stale tx
2472 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2473 check_added_monitors!(nodes[1], 1);
2474 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2475 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2476 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2478 check_spends!(node_txn[0], revoked_local_txn[0]);
2479 check_spends!(node_txn[1], chan_1.3);
2481 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2482 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2483 get_announce_close_broadcast_events(&nodes, 0, 1);
2484 check_added_monitors!(nodes[0], 1);
2485 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2489 fn claim_htlc_outputs_shared_tx() {
2490 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2491 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2492 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2493 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2494 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2495 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2497 // Create some new channel:
2498 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2500 // Rebalance the network to generate htlc in the two directions
2501 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2502 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2503 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2504 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2506 // Get the will-be-revoked local txn from node[0]
2507 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2508 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2509 assert_eq!(revoked_local_txn[0].input.len(), 1);
2510 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2511 assert_eq!(revoked_local_txn[1].input.len(), 1);
2512 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2513 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2514 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2516 //Revoke the old state
2517 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2520 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2521 check_added_monitors!(nodes[0], 1);
2522 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2523 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2524 check_added_monitors!(nodes[1], 1);
2525 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2526 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2527 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2529 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2530 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2532 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2533 check_spends!(node_txn[0], revoked_local_txn[0]);
2535 let mut witness_lens = BTreeSet::new();
2536 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2537 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2538 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2539 assert_eq!(witness_lens.len(), 3);
2540 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2541 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2542 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2544 // Next nodes[1] broadcasts its current local tx state:
2545 assert_eq!(node_txn[1].input.len(), 1);
2546 check_spends!(node_txn[1], chan_1.3);
2548 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2549 // ANTI_REORG_DELAY confirmations.
2550 mine_transaction(&nodes[1], &node_txn[0]);
2551 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2552 expect_payment_failed!(nodes[1], payment_hash_2, false);
2554 get_announce_close_broadcast_events(&nodes, 0, 1);
2555 assert_eq!(nodes[0].node.list_channels().len(), 0);
2556 assert_eq!(nodes[1].node.list_channels().len(), 0);
2560 fn claim_htlc_outputs_single_tx() {
2561 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2562 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2563 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2564 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2565 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2566 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2568 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2570 // Rebalance the network to generate htlc in the two directions
2571 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2572 // 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
2573 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2574 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2575 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2577 // Get the will-be-revoked local txn from node[0]
2578 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2580 //Revoke the old state
2581 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2584 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2585 check_added_monitors!(nodes[0], 1);
2586 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2587 check_added_monitors!(nodes[1], 1);
2588 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2589 let mut events = nodes[0].node.get_and_clear_pending_events();
2590 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2591 match events.last().unwrap() {
2592 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2593 _ => panic!("Unexpected event"),
2596 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2597 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2599 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2600 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2602 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2603 assert_eq!(node_txn[0].input.len(), 1);
2604 check_spends!(node_txn[0], chan_1.3);
2605 assert_eq!(node_txn[1].input.len(), 1);
2606 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2607 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2608 check_spends!(node_txn[1], node_txn[0]);
2610 // Justice transactions are indices 1-2-4
2611 assert_eq!(node_txn[2].input.len(), 1);
2612 assert_eq!(node_txn[3].input.len(), 1);
2613 assert_eq!(node_txn[4].input.len(), 1);
2615 check_spends!(node_txn[2], revoked_local_txn[0]);
2616 check_spends!(node_txn[3], revoked_local_txn[0]);
2617 check_spends!(node_txn[4], revoked_local_txn[0]);
2619 let mut witness_lens = BTreeSet::new();
2620 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2621 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2622 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2623 assert_eq!(witness_lens.len(), 3);
2624 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2625 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2626 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2628 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2629 // ANTI_REORG_DELAY confirmations.
2630 mine_transaction(&nodes[1], &node_txn[2]);
2631 mine_transaction(&nodes[1], &node_txn[3]);
2632 mine_transaction(&nodes[1], &node_txn[4]);
2633 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2634 expect_payment_failed!(nodes[1], payment_hash_2, false);
2636 get_announce_close_broadcast_events(&nodes, 0, 1);
2637 assert_eq!(nodes[0].node.list_channels().len(), 0);
2638 assert_eq!(nodes[1].node.list_channels().len(), 0);
2642 fn test_htlc_on_chain_success() {
2643 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2644 // the preimage backward accordingly. So here we test that ChannelManager is
2645 // broadcasting the right event to other nodes in payment path.
2646 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2647 // A --------------------> B ----------------------> C (preimage)
2648 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2649 // commitment transaction was broadcast.
2650 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2652 // B should be able to claim via preimage if A then broadcasts its local tx.
2653 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2654 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2655 // PaymentSent event).
2657 let chanmon_cfgs = create_chanmon_cfgs(3);
2658 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2659 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2660 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2662 // Create some initial channels
2663 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2664 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2666 // Ensure all nodes are at the same height
2667 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2668 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2669 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2670 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2672 // Rebalance the network a bit by relaying one payment through all the channels...
2673 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2674 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2676 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2677 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2679 // Broadcast legit commitment tx from C on B's chain
2680 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2681 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2682 assert_eq!(commitment_tx.len(), 1);
2683 check_spends!(commitment_tx[0], chan_2.3);
2684 nodes[2].node.claim_funds(our_payment_preimage);
2685 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2686 nodes[2].node.claim_funds(our_payment_preimage_2);
2687 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2688 check_added_monitors!(nodes[2], 2);
2689 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2690 assert!(updates.update_add_htlcs.is_empty());
2691 assert!(updates.update_fail_htlcs.is_empty());
2692 assert!(updates.update_fail_malformed_htlcs.is_empty());
2693 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2695 mine_transaction(&nodes[2], &commitment_tx[0]);
2696 check_closed_broadcast!(nodes[2], true);
2697 check_added_monitors!(nodes[2], 1);
2698 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2699 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)
2700 assert_eq!(node_txn.len(), 5);
2701 assert_eq!(node_txn[0], node_txn[3]);
2702 assert_eq!(node_txn[1], node_txn[4]);
2703 assert_eq!(node_txn[2], commitment_tx[0]);
2704 check_spends!(node_txn[0], commitment_tx[0]);
2705 check_spends!(node_txn[1], commitment_tx[0]);
2706 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2707 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2708 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2709 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2710 assert_eq!(node_txn[0].lock_time.0, 0);
2711 assert_eq!(node_txn[1].lock_time.0, 0);
2713 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2714 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2715 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2716 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2718 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2719 assert_eq!(added_monitors.len(), 1);
2720 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2721 added_monitors.clear();
2723 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2724 assert_eq!(forwarded_events.len(), 3);
2725 match forwarded_events[0] {
2726 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2727 _ => panic!("Unexpected event"),
2729 let chan_id = Some(chan_1.2);
2730 match forwarded_events[1] {
2731 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2732 assert_eq!(fee_earned_msat, Some(1000));
2733 assert_eq!(prev_channel_id, chan_id);
2734 assert_eq!(claim_from_onchain_tx, true);
2735 assert_eq!(next_channel_id, Some(chan_2.2));
2739 match forwarded_events[2] {
2740 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2741 assert_eq!(fee_earned_msat, Some(1000));
2742 assert_eq!(prev_channel_id, chan_id);
2743 assert_eq!(claim_from_onchain_tx, true);
2744 assert_eq!(next_channel_id, Some(chan_2.2));
2748 let events = nodes[1].node.get_and_clear_pending_msg_events();
2750 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2751 assert_eq!(added_monitors.len(), 2);
2752 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2753 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2754 added_monitors.clear();
2756 assert_eq!(events.len(), 3);
2758 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2759 _ => panic!("Unexpected event"),
2762 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2763 _ => panic!("Unexpected event"),
2767 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, .. } } => {
2768 assert!(update_add_htlcs.is_empty());
2769 assert!(update_fail_htlcs.is_empty());
2770 assert_eq!(update_fulfill_htlcs.len(), 1);
2771 assert!(update_fail_malformed_htlcs.is_empty());
2772 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2774 _ => panic!("Unexpected event"),
2776 macro_rules! check_tx_local_broadcast {
2777 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2778 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2779 assert_eq!(node_txn.len(), 3);
2780 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2781 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2782 check_spends!(node_txn[1], $commitment_tx);
2783 check_spends!(node_txn[2], $commitment_tx);
2784 assert_ne!(node_txn[1].lock_time.0, 0);
2785 assert_ne!(node_txn[2].lock_time.0, 0);
2787 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2788 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2789 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2790 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2792 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2793 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2794 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2795 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2797 check_spends!(node_txn[0], $chan_tx);
2798 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2802 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2803 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2804 // timeout-claim of the output that nodes[2] just claimed via success.
2805 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2807 // Broadcast legit commitment tx from A on B's chain
2808 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2809 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2810 check_spends!(node_a_commitment_tx[0], chan_1.3);
2811 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2812 check_closed_broadcast!(nodes[1], true);
2813 check_added_monitors!(nodes[1], 1);
2814 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2815 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2816 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2817 let commitment_spend =
2818 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2819 check_spends!(node_txn[1], commitment_tx[0]);
2820 check_spends!(node_txn[2], commitment_tx[0]);
2821 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2824 check_spends!(node_txn[0], commitment_tx[0]);
2825 check_spends!(node_txn[1], commitment_tx[0]);
2826 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2830 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2831 assert_eq!(commitment_spend.input.len(), 2);
2832 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2833 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2834 assert_eq!(commitment_spend.lock_time.0, 0);
2835 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2836 check_spends!(node_txn[3], chan_1.3);
2837 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2838 check_spends!(node_txn[4], node_txn[3]);
2839 check_spends!(node_txn[5], node_txn[3]);
2840 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2841 // we already checked the same situation with A.
2843 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2844 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2845 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2846 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2847 check_closed_broadcast!(nodes[0], true);
2848 check_added_monitors!(nodes[0], 1);
2849 let events = nodes[0].node.get_and_clear_pending_events();
2850 assert_eq!(events.len(), 5);
2851 let mut first_claimed = false;
2852 for event in events {
2854 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2855 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2856 assert!(!first_claimed);
2857 first_claimed = true;
2859 assert_eq!(payment_preimage, our_payment_preimage_2);
2860 assert_eq!(payment_hash, payment_hash_2);
2863 Event::PaymentPathSuccessful { .. } => {},
2864 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2865 _ => panic!("Unexpected event"),
2868 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2871 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2872 // Test that in case of a unilateral close onchain, we detect the state of output and
2873 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2874 // broadcasting the right event to other nodes in payment path.
2875 // A ------------------> B ----------------------> C (timeout)
2876 // B's commitment tx C's commitment tx
2878 // B's HTLC timeout tx B's timeout tx
2880 let chanmon_cfgs = create_chanmon_cfgs(3);
2881 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2882 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2883 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2884 *nodes[0].connect_style.borrow_mut() = connect_style;
2885 *nodes[1].connect_style.borrow_mut() = connect_style;
2886 *nodes[2].connect_style.borrow_mut() = connect_style;
2888 // Create some intial channels
2889 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2890 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2892 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2893 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2894 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2896 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2898 // Broadcast legit commitment tx from C on B's chain
2899 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2900 check_spends!(commitment_tx[0], chan_2.3);
2901 nodes[2].node.fail_htlc_backwards(&payment_hash);
2902 check_added_monitors!(nodes[2], 0);
2903 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2904 check_added_monitors!(nodes[2], 1);
2906 let events = nodes[2].node.get_and_clear_pending_msg_events();
2907 assert_eq!(events.len(), 1);
2909 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, .. } } => {
2910 assert!(update_add_htlcs.is_empty());
2911 assert!(!update_fail_htlcs.is_empty());
2912 assert!(update_fulfill_htlcs.is_empty());
2913 assert!(update_fail_malformed_htlcs.is_empty());
2914 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2916 _ => panic!("Unexpected event"),
2918 mine_transaction(&nodes[2], &commitment_tx[0]);
2919 check_closed_broadcast!(nodes[2], true);
2920 check_added_monitors!(nodes[2], 1);
2921 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2922 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2923 assert_eq!(node_txn.len(), 1);
2924 check_spends!(node_txn[0], chan_2.3);
2925 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2927 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2928 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2929 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2930 mine_transaction(&nodes[1], &commitment_tx[0]);
2931 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2934 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2935 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2936 assert_eq!(node_txn[0], node_txn[3]);
2937 assert_eq!(node_txn[1], node_txn[4]);
2939 check_spends!(node_txn[2], commitment_tx[0]);
2940 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2942 check_spends!(node_txn[0], chan_2.3);
2943 check_spends!(node_txn[1], node_txn[0]);
2944 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2945 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2947 timeout_tx = node_txn[2].clone();
2951 mine_transaction(&nodes[1], &timeout_tx);
2952 check_added_monitors!(nodes[1], 1);
2953 check_closed_broadcast!(nodes[1], true);
2955 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2957 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 }]);
2958 check_added_monitors!(nodes[1], 1);
2959 let events = nodes[1].node.get_and_clear_pending_msg_events();
2960 assert_eq!(events.len(), 1);
2962 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, .. } } => {
2963 assert!(update_add_htlcs.is_empty());
2964 assert!(!update_fail_htlcs.is_empty());
2965 assert!(update_fulfill_htlcs.is_empty());
2966 assert!(update_fail_malformed_htlcs.is_empty());
2967 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2969 _ => panic!("Unexpected event"),
2972 // Broadcast legit commitment tx from B on A's chain
2973 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2974 check_spends!(commitment_tx[0], chan_1.3);
2976 mine_transaction(&nodes[0], &commitment_tx[0]);
2977 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2979 check_closed_broadcast!(nodes[0], true);
2980 check_added_monitors!(nodes[0], 1);
2981 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2982 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2983 assert_eq!(node_txn.len(), 2);
2984 check_spends!(node_txn[0], chan_1.3);
2985 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2986 check_spends!(node_txn[1], commitment_tx[0]);
2987 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2991 fn test_htlc_on_chain_timeout() {
2992 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2993 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2994 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2998 fn test_simple_commitment_revoked_fail_backward() {
2999 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3000 // and fail backward accordingly.
3002 let chanmon_cfgs = create_chanmon_cfgs(3);
3003 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3004 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3005 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3007 // Create some initial channels
3008 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3009 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3011 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3012 // Get the will-be-revoked local txn from nodes[2]
3013 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3014 // Revoke the old state
3015 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3017 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3019 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3020 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3021 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3022 check_added_monitors!(nodes[1], 1);
3023 check_closed_broadcast!(nodes[1], true);
3025 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 }]);
3026 check_added_monitors!(nodes[1], 1);
3027 let events = nodes[1].node.get_and_clear_pending_msg_events();
3028 assert_eq!(events.len(), 1);
3030 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, .. } } => {
3031 assert!(update_add_htlcs.is_empty());
3032 assert_eq!(update_fail_htlcs.len(), 1);
3033 assert!(update_fulfill_htlcs.is_empty());
3034 assert!(update_fail_malformed_htlcs.is_empty());
3035 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3037 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3038 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3039 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3041 _ => panic!("Unexpected event"),
3045 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3046 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3047 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3048 // commitment transaction anymore.
3049 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3050 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3051 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3052 // technically disallowed and we should probably handle it reasonably.
3053 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3054 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3056 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3057 // commitment_signed (implying it will be in the latest remote commitment transaction).
3058 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3059 // and once they revoke the previous commitment transaction (allowing us to send a new
3060 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3061 let chanmon_cfgs = create_chanmon_cfgs(3);
3062 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3063 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3064 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3066 // Create some initial channels
3067 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3068 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3070 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 });
3071 // Get the will-be-revoked local txn from nodes[2]
3072 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3073 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3074 // Revoke the old state
3075 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3077 let value = if use_dust {
3078 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3079 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3080 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3083 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3084 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3085 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3087 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3088 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3089 check_added_monitors!(nodes[2], 1);
3090 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3091 assert!(updates.update_add_htlcs.is_empty());
3092 assert!(updates.update_fulfill_htlcs.is_empty());
3093 assert!(updates.update_fail_malformed_htlcs.is_empty());
3094 assert_eq!(updates.update_fail_htlcs.len(), 1);
3095 assert!(updates.update_fee.is_none());
3096 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3097 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3098 // Drop the last RAA from 3 -> 2
3100 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3101 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3102 check_added_monitors!(nodes[2], 1);
3103 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3104 assert!(updates.update_add_htlcs.is_empty());
3105 assert!(updates.update_fulfill_htlcs.is_empty());
3106 assert!(updates.update_fail_malformed_htlcs.is_empty());
3107 assert_eq!(updates.update_fail_htlcs.len(), 1);
3108 assert!(updates.update_fee.is_none());
3109 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3110 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3111 check_added_monitors!(nodes[1], 1);
3112 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3113 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3114 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3115 check_added_monitors!(nodes[2], 1);
3117 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3118 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3119 check_added_monitors!(nodes[2], 1);
3120 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3121 assert!(updates.update_add_htlcs.is_empty());
3122 assert!(updates.update_fulfill_htlcs.is_empty());
3123 assert!(updates.update_fail_malformed_htlcs.is_empty());
3124 assert_eq!(updates.update_fail_htlcs.len(), 1);
3125 assert!(updates.update_fee.is_none());
3126 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3127 // At this point first_payment_hash has dropped out of the latest two commitment
3128 // transactions that nodes[1] is tracking...
3129 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3130 check_added_monitors!(nodes[1], 1);
3131 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3132 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3133 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3134 check_added_monitors!(nodes[2], 1);
3136 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3137 // on nodes[2]'s RAA.
3138 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3139 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3140 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3141 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3142 check_added_monitors!(nodes[1], 0);
3145 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3146 // One monitor for the new revocation preimage, no second on as we won't generate a new
3147 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3148 check_added_monitors!(nodes[1], 1);
3149 let events = nodes[1].node.get_and_clear_pending_events();
3150 assert_eq!(events.len(), 2);
3152 Event::PendingHTLCsForwardable { .. } => { },
3153 _ => panic!("Unexpected event"),
3156 Event::HTLCHandlingFailed { .. } => { },
3157 _ => panic!("Unexpected event"),
3159 // Deliberately don't process the pending fail-back so they all fail back at once after
3160 // block connection just like the !deliver_bs_raa case
3163 let mut failed_htlcs = HashSet::new();
3164 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3166 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3167 check_added_monitors!(nodes[1], 1);
3168 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3169 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3171 let events = nodes[1].node.get_and_clear_pending_events();
3172 assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3174 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3175 _ => panic!("Unexepected event"),
3178 Event::PaymentPathFailed { ref payment_hash, .. } => {
3179 assert_eq!(*payment_hash, fourth_payment_hash);
3181 _ => panic!("Unexpected event"),
3183 if !deliver_bs_raa {
3185 Event::PaymentFailed { ref payment_hash, .. } => {
3186 assert_eq!(*payment_hash, fourth_payment_hash);
3188 _ => panic!("Unexpected event"),
3191 Event::PendingHTLCsForwardable { .. } => { },
3192 _ => panic!("Unexpected event"),
3195 nodes[1].node.process_pending_htlc_forwards();
3196 check_added_monitors!(nodes[1], 1);
3198 let events = nodes[1].node.get_and_clear_pending_msg_events();
3199 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3200 match events[if deliver_bs_raa { 1 } else { 0 }] {
3201 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3202 _ => panic!("Unexpected event"),
3204 match events[if deliver_bs_raa { 2 } else { 1 }] {
3205 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3206 assert_eq!(channel_id, chan_2.2);
3207 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3209 _ => panic!("Unexpected event"),
3213 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, .. } } => {
3214 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3215 assert_eq!(update_add_htlcs.len(), 1);
3216 assert!(update_fulfill_htlcs.is_empty());
3217 assert!(update_fail_htlcs.is_empty());
3218 assert!(update_fail_malformed_htlcs.is_empty());
3220 _ => panic!("Unexpected event"),
3223 match events[if deliver_bs_raa { 3 } else { 2 }] {
3224 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, .. } } => {
3225 assert!(update_add_htlcs.is_empty());
3226 assert_eq!(update_fail_htlcs.len(), 3);
3227 assert!(update_fulfill_htlcs.is_empty());
3228 assert!(update_fail_malformed_htlcs.is_empty());
3229 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3231 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3232 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3233 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3235 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3237 let events = nodes[0].node.get_and_clear_pending_events();
3238 assert_eq!(events.len(), 3);
3240 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3241 assert!(failed_htlcs.insert(payment_hash.0));
3242 // If we delivered B's RAA we got an unknown preimage error, not something
3243 // that we should update our routing table for.
3244 if !deliver_bs_raa {
3245 assert!(network_update.is_some());
3248 _ => panic!("Unexpected event"),
3251 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3252 assert!(failed_htlcs.insert(payment_hash.0));
3253 assert!(network_update.is_some());
3255 _ => panic!("Unexpected event"),
3258 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3259 assert!(failed_htlcs.insert(payment_hash.0));
3260 assert!(network_update.is_some());
3262 _ => panic!("Unexpected event"),
3265 _ => panic!("Unexpected event"),
3268 assert!(failed_htlcs.contains(&first_payment_hash.0));
3269 assert!(failed_htlcs.contains(&second_payment_hash.0));
3270 assert!(failed_htlcs.contains(&third_payment_hash.0));
3274 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3275 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3276 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3277 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3278 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3282 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3283 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3284 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3285 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3286 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3290 fn fail_backward_pending_htlc_upon_channel_failure() {
3291 let chanmon_cfgs = create_chanmon_cfgs(2);
3292 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3293 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3294 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3295 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());
3297 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3299 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3300 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3301 check_added_monitors!(nodes[0], 1);
3303 let payment_event = {
3304 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3305 assert_eq!(events.len(), 1);
3306 SendEvent::from_event(events.remove(0))
3308 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3309 assert_eq!(payment_event.msgs.len(), 1);
3312 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3313 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3315 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3316 check_added_monitors!(nodes[0], 0);
3318 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3321 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3323 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3325 let secp_ctx = Secp256k1::new();
3326 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3327 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3328 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3329 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3330 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3332 // Send a 0-msat update_add_htlc to fail the channel.
3333 let update_add_htlc = msgs::UpdateAddHTLC {
3339 onion_routing_packet,
3341 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3343 let events = nodes[0].node.get_and_clear_pending_events();
3344 assert_eq!(events.len(), 2);
3345 // Check that Alice fails backward the pending HTLC from the second payment.
3347 Event::PaymentPathFailed { payment_hash, .. } => {
3348 assert_eq!(payment_hash, failed_payment_hash);
3350 _ => panic!("Unexpected event"),
3353 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3354 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3356 _ => panic!("Unexpected event {:?}", events[1]),
3358 check_closed_broadcast!(nodes[0], true);
3359 check_added_monitors!(nodes[0], 1);
3363 fn test_htlc_ignore_latest_remote_commitment() {
3364 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3365 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3366 let chanmon_cfgs = create_chanmon_cfgs(2);
3367 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3368 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3369 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3370 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3372 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3373 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3374 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3375 check_closed_broadcast!(nodes[0], true);
3376 check_added_monitors!(nodes[0], 1);
3377 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3379 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3380 assert_eq!(node_txn.len(), 3);
3381 assert_eq!(node_txn[0], node_txn[1]);
3383 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3384 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3385 check_closed_broadcast!(nodes[1], true);
3386 check_added_monitors!(nodes[1], 1);
3387 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3389 // Duplicate the connect_block call since this may happen due to other listeners
3390 // registering new transactions
3391 header.prev_blockhash = header.block_hash();
3392 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3396 fn test_force_close_fail_back() {
3397 // Check which HTLCs are failed-backwards on channel force-closure
3398 let chanmon_cfgs = create_chanmon_cfgs(3);
3399 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3400 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3401 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3402 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3403 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3405 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3407 let mut payment_event = {
3408 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3409 check_added_monitors!(nodes[0], 1);
3411 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3412 assert_eq!(events.len(), 1);
3413 SendEvent::from_event(events.remove(0))
3416 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3417 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3419 expect_pending_htlcs_forwardable!(nodes[1]);
3421 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3422 assert_eq!(events_2.len(), 1);
3423 payment_event = SendEvent::from_event(events_2.remove(0));
3424 assert_eq!(payment_event.msgs.len(), 1);
3426 check_added_monitors!(nodes[1], 1);
3427 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3428 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3429 check_added_monitors!(nodes[2], 1);
3430 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3432 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3433 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3434 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3436 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3437 check_closed_broadcast!(nodes[2], true);
3438 check_added_monitors!(nodes[2], 1);
3439 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3441 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3442 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3443 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3444 // back to nodes[1] upon timeout otherwise.
3445 assert_eq!(node_txn.len(), 1);
3449 mine_transaction(&nodes[1], &tx);
3451 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3452 check_closed_broadcast!(nodes[1], true);
3453 check_added_monitors!(nodes[1], 1);
3454 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3456 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3458 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3459 .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);
3461 mine_transaction(&nodes[2], &tx);
3462 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3463 assert_eq!(node_txn.len(), 1);
3464 assert_eq!(node_txn[0].input.len(), 1);
3465 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3466 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3467 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3469 check_spends!(node_txn[0], tx);
3473 fn test_dup_events_on_peer_disconnect() {
3474 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3475 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3476 // as we used to generate the event immediately upon receipt of the payment preimage in the
3477 // update_fulfill_htlc message.
3479 let chanmon_cfgs = create_chanmon_cfgs(2);
3480 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3481 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3482 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3483 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3485 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3487 nodes[1].node.claim_funds(payment_preimage);
3488 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3489 check_added_monitors!(nodes[1], 1);
3490 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3491 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3492 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3494 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3495 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3497 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3498 expect_payment_path_successful!(nodes[0]);
3502 fn test_peer_disconnected_before_funding_broadcasted() {
3503 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3504 // before the funding transaction has been broadcasted.
3505 let chanmon_cfgs = create_chanmon_cfgs(2);
3506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3510 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3511 // broadcasted, even though it's created by `nodes[0]`.
3512 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();
3513 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3514 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3515 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3516 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3518 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3519 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3521 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3523 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3524 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3526 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3527 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3530 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3533 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3534 // disconnected before the funding transaction was broadcasted.
3535 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3536 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3538 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3539 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3543 fn test_simple_peer_disconnect() {
3544 // Test that we can reconnect when there are no lost messages
3545 let chanmon_cfgs = create_chanmon_cfgs(3);
3546 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3547 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3548 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3549 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3550 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3552 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3553 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3554 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3556 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3557 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3558 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3559 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3561 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3562 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3563 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3565 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3566 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3567 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3568 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3570 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3571 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3574 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3576 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3578 let events = nodes[0].node.get_and_clear_pending_events();
3579 assert_eq!(events.len(), 3);
3581 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3582 assert_eq!(payment_preimage, payment_preimage_3);
3583 assert_eq!(payment_hash, payment_hash_3);
3585 _ => panic!("Unexpected event"),
3588 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3589 assert_eq!(payment_hash, payment_hash_5);
3590 assert!(payment_failed_permanently);
3592 _ => panic!("Unexpected event"),
3595 Event::PaymentPathSuccessful { .. } => {},
3596 _ => panic!("Unexpected event"),
3600 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3601 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3604 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3605 // Test that we can reconnect when in-flight HTLC updates get dropped
3606 let chanmon_cfgs = create_chanmon_cfgs(2);
3607 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3608 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3609 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3611 let mut as_channel_ready = None;
3612 if messages_delivered == 0 {
3613 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3614 as_channel_ready = Some(channel_ready);
3615 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3616 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3617 // it before the channel_reestablish message.
3619 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3622 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3624 let payment_event = {
3625 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3626 check_added_monitors!(nodes[0], 1);
3628 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3629 assert_eq!(events.len(), 1);
3630 SendEvent::from_event(events.remove(0))
3632 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3634 if messages_delivered < 2 {
3635 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3637 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3638 if messages_delivered >= 3 {
3639 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3640 check_added_monitors!(nodes[1], 1);
3641 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3643 if messages_delivered >= 4 {
3644 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3645 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3646 check_added_monitors!(nodes[0], 1);
3648 if messages_delivered >= 5 {
3649 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3650 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3651 // No commitment_signed so get_event_msg's assert(len == 1) passes
3652 check_added_monitors!(nodes[0], 1);
3654 if messages_delivered >= 6 {
3655 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3656 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3657 check_added_monitors!(nodes[1], 1);
3664 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3665 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3666 if messages_delivered < 3 {
3667 if simulate_broken_lnd {
3668 // lnd has a long-standing bug where they send a channel_ready prior to a
3669 // channel_reestablish if you reconnect prior to channel_ready time.
3671 // Here we simulate that behavior, delivering a channel_ready immediately on
3672 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3673 // in `reconnect_nodes` but we currently don't fail based on that.
3675 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3676 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3678 // Even if the channel_ready messages get exchanged, as long as nothing further was
3679 // received on either side, both sides will need to resend them.
3680 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3681 } else if messages_delivered == 3 {
3682 // nodes[0] still wants its RAA + commitment_signed
3683 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3684 } else if messages_delivered == 4 {
3685 // nodes[0] still wants its commitment_signed
3686 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3687 } else if messages_delivered == 5 {
3688 // nodes[1] still wants its final RAA
3689 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3690 } else if messages_delivered == 6 {
3691 // Everything was delivered...
3692 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3695 let events_1 = nodes[1].node.get_and_clear_pending_events();
3696 assert_eq!(events_1.len(), 1);
3698 Event::PendingHTLCsForwardable { .. } => { },
3699 _ => panic!("Unexpected event"),
3702 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3703 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3704 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3706 nodes[1].node.process_pending_htlc_forwards();
3708 let events_2 = nodes[1].node.get_and_clear_pending_events();
3709 assert_eq!(events_2.len(), 1);
3711 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3712 assert_eq!(payment_hash_1, *payment_hash);
3713 assert_eq!(amount_msat, 1_000_000);
3715 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3716 assert!(payment_preimage.is_none());
3717 assert_eq!(payment_secret_1, *payment_secret);
3719 _ => panic!("expected PaymentPurpose::InvoicePayment")
3722 _ => panic!("Unexpected event"),
3725 nodes[1].node.claim_funds(payment_preimage_1);
3726 check_added_monitors!(nodes[1], 1);
3727 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3729 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3730 assert_eq!(events_3.len(), 1);
3731 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3732 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3733 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3734 assert!(updates.update_add_htlcs.is_empty());
3735 assert!(updates.update_fail_htlcs.is_empty());
3736 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3737 assert!(updates.update_fail_malformed_htlcs.is_empty());
3738 assert!(updates.update_fee.is_none());
3739 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3741 _ => panic!("Unexpected event"),
3744 if messages_delivered >= 1 {
3745 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3747 let events_4 = nodes[0].node.get_and_clear_pending_events();
3748 assert_eq!(events_4.len(), 1);
3750 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3751 assert_eq!(payment_preimage_1, *payment_preimage);
3752 assert_eq!(payment_hash_1, *payment_hash);
3754 _ => panic!("Unexpected event"),
3757 if messages_delivered >= 2 {
3758 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3759 check_added_monitors!(nodes[0], 1);
3760 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3762 if messages_delivered >= 3 {
3763 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3764 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3765 check_added_monitors!(nodes[1], 1);
3767 if messages_delivered >= 4 {
3768 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3769 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3770 // No commitment_signed so get_event_msg's assert(len == 1) passes
3771 check_added_monitors!(nodes[1], 1);
3773 if messages_delivered >= 5 {
3774 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3775 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3776 check_added_monitors!(nodes[0], 1);
3783 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3784 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3785 if messages_delivered < 2 {
3786 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3787 if messages_delivered < 1 {
3788 expect_payment_sent!(nodes[0], payment_preimage_1);
3790 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3792 } else if messages_delivered == 2 {
3793 // nodes[0] still wants its RAA + commitment_signed
3794 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3795 } else if messages_delivered == 3 {
3796 // nodes[0] still wants its commitment_signed
3797 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3798 } else if messages_delivered == 4 {
3799 // nodes[1] still wants its final RAA
3800 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3801 } else if messages_delivered == 5 {
3802 // Everything was delivered...
3803 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3806 if messages_delivered == 1 || messages_delivered == 2 {
3807 expect_payment_path_successful!(nodes[0]);
3810 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3811 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3812 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3814 if messages_delivered > 2 {
3815 expect_payment_path_successful!(nodes[0]);
3818 // Channel should still work fine...
3819 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3820 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3821 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3825 fn test_drop_messages_peer_disconnect_a() {
3826 do_test_drop_messages_peer_disconnect(0, true);
3827 do_test_drop_messages_peer_disconnect(0, false);
3828 do_test_drop_messages_peer_disconnect(1, false);
3829 do_test_drop_messages_peer_disconnect(2, false);
3833 fn test_drop_messages_peer_disconnect_b() {
3834 do_test_drop_messages_peer_disconnect(3, false);
3835 do_test_drop_messages_peer_disconnect(4, false);
3836 do_test_drop_messages_peer_disconnect(5, false);
3837 do_test_drop_messages_peer_disconnect(6, false);
3841 fn test_funding_peer_disconnect() {
3842 // Test that we can lock in our funding tx while disconnected
3843 let chanmon_cfgs = create_chanmon_cfgs(2);
3844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3845 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3846 let persister: test_utils::TestPersister;
3847 let new_chain_monitor: test_utils::TestChainMonitor;
3848 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3849 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3850 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3852 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3853 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3855 confirm_transaction(&nodes[0], &tx);
3856 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3857 assert!(events_1.is_empty());
3859 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3861 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3862 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3864 confirm_transaction(&nodes[1], &tx);
3865 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3866 assert!(events_2.is_empty());
3868 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3869 let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
3870 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3871 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
3873 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3874 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3875 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3876 assert_eq!(events_3.len(), 1);
3877 let as_channel_ready = match events_3[0] {
3878 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3879 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3882 _ => panic!("Unexpected event {:?}", events_3[0]),
3885 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3886 // announcement_signatures as well as channel_update.
3887 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3888 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3889 assert_eq!(events_4.len(), 3);
3891 let bs_channel_ready = match events_4[0] {
3892 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3893 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3894 chan_id = msg.channel_id;
3897 _ => panic!("Unexpected event {:?}", events_4[0]),
3899 let bs_announcement_sigs = match events_4[1] {
3900 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3901 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3904 _ => panic!("Unexpected event {:?}", events_4[1]),
3907 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3908 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3910 _ => panic!("Unexpected event {:?}", events_4[2]),
3913 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3914 // generates a duplicative private channel_update
3915 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3916 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3917 assert_eq!(events_5.len(), 1);
3919 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3920 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3922 _ => panic!("Unexpected event {:?}", events_5[0]),
3925 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3926 // announcement_signatures.
3927 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3928 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3929 assert_eq!(events_6.len(), 1);
3930 let as_announcement_sigs = match events_6[0] {
3931 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3932 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3935 _ => panic!("Unexpected event {:?}", events_6[0]),
3938 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3939 // broadcast the channel announcement globally, as well as re-send its (now-public)
3941 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3942 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3943 assert_eq!(events_7.len(), 1);
3944 let (chan_announcement, as_update) = match events_7[0] {
3945 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3946 (msg.clone(), update_msg.clone())
3948 _ => panic!("Unexpected event {:?}", events_7[0]),
3951 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3952 // same channel_announcement.
3953 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3954 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3955 assert_eq!(events_8.len(), 1);
3956 let bs_update = match events_8[0] {
3957 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3958 assert_eq!(*msg, chan_announcement);
3961 _ => panic!("Unexpected event {:?}", events_8[0]),
3964 // Provide the channel announcement and public updates to the network graph
3965 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3966 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3967 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3969 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3970 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3971 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3973 // Check that after deserialization and reconnection we can still generate an identical
3974 // channel_announcement from the cached signatures.
3975 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3977 let nodes_0_serialized = nodes[0].node.encode();
3978 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3979 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3981 persister = test_utils::TestPersister::new();
3982 let keys_manager = &chanmon_cfgs[0].keys_manager;
3983 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);
3984 nodes[0].chain_monitor = &new_chain_monitor;
3985 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3986 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3987 &mut chan_0_monitor_read, keys_manager).unwrap();
3988 assert!(chan_0_monitor_read.is_empty());
3990 let mut nodes_0_read = &nodes_0_serialized[..];
3991 let (_, nodes_0_deserialized_tmp) = {
3992 let mut channel_monitors = HashMap::new();
3993 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3994 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3995 default_config: UserConfig::default(),
3997 fee_estimator: node_cfgs[0].fee_estimator,
3998 chain_monitor: nodes[0].chain_monitor,
3999 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4000 logger: nodes[0].logger,
4004 nodes_0_deserialized = nodes_0_deserialized_tmp;
4005 assert!(nodes_0_read.is_empty());
4007 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4008 ChannelMonitorUpdateStatus::Completed);
4009 nodes[0].node = &nodes_0_deserialized;
4010 check_added_monitors!(nodes[0], 1);
4012 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4016 fn test_channel_ready_without_best_block_updated() {
4017 // Previously, if we were offline when a funding transaction was locked in, and then we came
4018 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4019 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4020 // channel_ready immediately instead.
4021 let chanmon_cfgs = create_chanmon_cfgs(2);
4022 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4023 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4024 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4025 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4027 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());
4029 let conf_height = nodes[0].best_block_info().1 + 1;
4030 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4031 let block_txn = [funding_tx];
4032 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4033 let conf_block_header = nodes[0].get_block_header(conf_height);
4034 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4036 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4037 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4038 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4042 fn test_drop_messages_peer_disconnect_dual_htlc() {
4043 // Test that we can handle reconnecting when both sides of a channel have pending
4044 // commitment_updates when we disconnect.
4045 let chanmon_cfgs = create_chanmon_cfgs(2);
4046 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4047 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4048 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4049 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4051 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4053 // Now try to send a second payment which will fail to send
4054 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4055 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4056 check_added_monitors!(nodes[0], 1);
4058 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4059 assert_eq!(events_1.len(), 1);
4061 MessageSendEvent::UpdateHTLCs { .. } => {},
4062 _ => panic!("Unexpected event"),
4065 nodes[1].node.claim_funds(payment_preimage_1);
4066 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4067 check_added_monitors!(nodes[1], 1);
4069 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4070 assert_eq!(events_2.len(), 1);
4072 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 } } => {
4073 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4074 assert!(update_add_htlcs.is_empty());
4075 assert_eq!(update_fulfill_htlcs.len(), 1);
4076 assert!(update_fail_htlcs.is_empty());
4077 assert!(update_fail_malformed_htlcs.is_empty());
4078 assert!(update_fee.is_none());
4080 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4081 let events_3 = nodes[0].node.get_and_clear_pending_events();
4082 assert_eq!(events_3.len(), 1);
4084 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4085 assert_eq!(*payment_preimage, payment_preimage_1);
4086 assert_eq!(*payment_hash, payment_hash_1);
4088 _ => panic!("Unexpected event"),
4091 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4092 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4093 // No commitment_signed so get_event_msg's assert(len == 1) passes
4094 check_added_monitors!(nodes[0], 1);
4096 _ => panic!("Unexpected event"),
4099 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4100 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4102 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4103 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4104 assert_eq!(reestablish_1.len(), 1);
4105 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4106 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4107 assert_eq!(reestablish_2.len(), 1);
4109 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4110 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4111 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4112 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4114 assert!(as_resp.0.is_none());
4115 assert!(bs_resp.0.is_none());
4117 assert!(bs_resp.1.is_none());
4118 assert!(bs_resp.2.is_none());
4120 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4122 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4123 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4124 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4125 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4126 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4127 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4128 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4129 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4130 // No commitment_signed so get_event_msg's assert(len == 1) passes
4131 check_added_monitors!(nodes[1], 1);
4133 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4134 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4135 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4136 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4137 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4138 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4139 assert!(bs_second_commitment_signed.update_fee.is_none());
4140 check_added_monitors!(nodes[1], 1);
4142 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4143 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4144 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4145 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4146 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4147 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4148 assert!(as_commitment_signed.update_fee.is_none());
4149 check_added_monitors!(nodes[0], 1);
4151 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4152 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4153 // No commitment_signed so get_event_msg's assert(len == 1) passes
4154 check_added_monitors!(nodes[0], 1);
4156 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4157 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4158 // No commitment_signed so get_event_msg's assert(len == 1) passes
4159 check_added_monitors!(nodes[1], 1);
4161 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4162 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4163 check_added_monitors!(nodes[1], 1);
4165 expect_pending_htlcs_forwardable!(nodes[1]);
4167 let events_5 = nodes[1].node.get_and_clear_pending_events();
4168 assert_eq!(events_5.len(), 1);
4170 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4171 assert_eq!(payment_hash_2, *payment_hash);
4173 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4174 assert!(payment_preimage.is_none());
4175 assert_eq!(payment_secret_2, *payment_secret);
4177 _ => panic!("expected PaymentPurpose::InvoicePayment")
4180 _ => panic!("Unexpected event"),
4183 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4184 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4185 check_added_monitors!(nodes[0], 1);
4187 expect_payment_path_successful!(nodes[0]);
4188 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4191 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4192 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4193 // to avoid our counterparty failing the channel.
4194 let chanmon_cfgs = create_chanmon_cfgs(2);
4195 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4196 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4197 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4199 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4201 let our_payment_hash = if send_partial_mpp {
4202 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4203 // Use the utility function send_payment_along_path to send the payment with MPP data which
4204 // indicates there are more HTLCs coming.
4205 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.
4206 let payment_id = PaymentId([42; 32]);
4207 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();
4208 check_added_monitors!(nodes[0], 1);
4209 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4210 assert_eq!(events.len(), 1);
4211 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4212 // hop should *not* yet generate any PaymentReceived event(s).
4213 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4216 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4219 let mut block = Block {
4220 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4223 connect_block(&nodes[0], &block);
4224 connect_block(&nodes[1], &block);
4225 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4226 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4227 block.header.prev_blockhash = block.block_hash();
4228 connect_block(&nodes[0], &block);
4229 connect_block(&nodes[1], &block);
4232 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4234 check_added_monitors!(nodes[1], 1);
4235 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4236 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4237 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4238 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4239 assert!(htlc_timeout_updates.update_fee.is_none());
4241 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4242 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4243 // 100_000 msat as u64, followed by the height at which we failed back above
4244 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4245 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4246 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4250 fn test_htlc_timeout() {
4251 do_test_htlc_timeout(true);
4252 do_test_htlc_timeout(false);
4255 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4256 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4257 let chanmon_cfgs = create_chanmon_cfgs(3);
4258 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4259 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4260 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4261 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4262 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4264 // Make sure all nodes are at the same starting height
4265 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4266 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4267 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4269 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4270 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4272 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4274 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4275 check_added_monitors!(nodes[1], 1);
4277 // Now attempt to route a second payment, which should be placed in the holding cell
4278 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4279 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4280 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4282 check_added_monitors!(nodes[0], 1);
4283 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4284 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4285 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4286 expect_pending_htlcs_forwardable!(nodes[1]);
4288 check_added_monitors!(nodes[1], 0);
4290 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4291 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4292 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4293 connect_blocks(&nodes[1], 1);
4296 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 }]);
4297 check_added_monitors!(nodes[1], 1);
4298 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4299 assert_eq!(fail_commit.len(), 1);
4300 match fail_commit[0] {
4301 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4303 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4305 _ => unreachable!(),
4307 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4309 let events = nodes[1].node.get_and_clear_pending_events();
4310 assert_eq!(events.len(), 2);
4311 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4312 assert_eq!(*payment_hash, second_payment_hash);
4313 } else { panic!("Unexpected event"); }
4314 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4315 assert_eq!(*payment_hash, second_payment_hash);
4316 } else { panic!("Unexpected event"); }
4321 fn test_holding_cell_htlc_add_timeouts() {
4322 do_test_holding_cell_htlc_add_timeouts(false);
4323 do_test_holding_cell_htlc_add_timeouts(true);
4327 fn test_no_txn_manager_serialize_deserialize() {
4328 let chanmon_cfgs = create_chanmon_cfgs(2);
4329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4331 let logger: test_utils::TestLogger;
4332 let fee_estimator: test_utils::TestFeeEstimator;
4333 let persister: test_utils::TestPersister;
4334 let new_chain_monitor: test_utils::TestChainMonitor;
4335 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4336 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4338 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4340 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4342 let nodes_0_serialized = nodes[0].node.encode();
4343 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4344 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4345 .write(&mut chan_0_monitor_serialized).unwrap();
4347 logger = test_utils::TestLogger::new();
4348 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4349 persister = test_utils::TestPersister::new();
4350 let keys_manager = &chanmon_cfgs[0].keys_manager;
4351 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4352 nodes[0].chain_monitor = &new_chain_monitor;
4353 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4354 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4355 &mut chan_0_monitor_read, keys_manager).unwrap();
4356 assert!(chan_0_monitor_read.is_empty());
4358 let mut nodes_0_read = &nodes_0_serialized[..];
4359 let config = UserConfig::default();
4360 let (_, nodes_0_deserialized_tmp) = {
4361 let mut channel_monitors = HashMap::new();
4362 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4363 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4364 default_config: config,
4366 fee_estimator: &fee_estimator,
4367 chain_monitor: nodes[0].chain_monitor,
4368 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4373 nodes_0_deserialized = nodes_0_deserialized_tmp;
4374 assert!(nodes_0_read.is_empty());
4376 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4377 ChannelMonitorUpdateStatus::Completed);
4378 nodes[0].node = &nodes_0_deserialized;
4379 assert_eq!(nodes[0].node.list_channels().len(), 1);
4380 check_added_monitors!(nodes[0], 1);
4382 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4383 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4384 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4385 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4387 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4388 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4389 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4390 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4392 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4393 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4394 for node in nodes.iter() {
4395 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4396 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4397 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4400 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4404 fn test_manager_serialize_deserialize_events() {
4405 // This test makes sure the events field in ChannelManager survives de/serialization
4406 let chanmon_cfgs = create_chanmon_cfgs(2);
4407 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4408 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4409 let fee_estimator: test_utils::TestFeeEstimator;
4410 let persister: test_utils::TestPersister;
4411 let logger: test_utils::TestLogger;
4412 let new_chain_monitor: test_utils::TestChainMonitor;
4413 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4414 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4416 // Start creating a channel, but stop right before broadcasting the funding transaction
4417 let channel_value = 100000;
4418 let push_msat = 10001;
4419 let a_flags = channelmanager::provided_init_features();
4420 let b_flags = channelmanager::provided_init_features();
4421 let node_a = nodes.remove(0);
4422 let node_b = nodes.remove(0);
4423 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4424 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()));
4425 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()));
4427 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4429 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4430 check_added_monitors!(node_a, 0);
4432 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()));
4434 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4435 assert_eq!(added_monitors.len(), 1);
4436 assert_eq!(added_monitors[0].0, funding_output);
4437 added_monitors.clear();
4440 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4441 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4443 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4444 assert_eq!(added_monitors.len(), 1);
4445 assert_eq!(added_monitors[0].0, funding_output);
4446 added_monitors.clear();
4448 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4453 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4454 let nodes_0_serialized = nodes[0].node.encode();
4455 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4456 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4458 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4459 logger = test_utils::TestLogger::new();
4460 persister = test_utils::TestPersister::new();
4461 let keys_manager = &chanmon_cfgs[0].keys_manager;
4462 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4463 nodes[0].chain_monitor = &new_chain_monitor;
4464 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4465 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4466 &mut chan_0_monitor_read, keys_manager).unwrap();
4467 assert!(chan_0_monitor_read.is_empty());
4469 let mut nodes_0_read = &nodes_0_serialized[..];
4470 let config = UserConfig::default();
4471 let (_, nodes_0_deserialized_tmp) = {
4472 let mut channel_monitors = HashMap::new();
4473 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4474 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4475 default_config: config,
4477 fee_estimator: &fee_estimator,
4478 chain_monitor: nodes[0].chain_monitor,
4479 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4484 nodes_0_deserialized = nodes_0_deserialized_tmp;
4485 assert!(nodes_0_read.is_empty());
4487 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4489 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4490 ChannelMonitorUpdateStatus::Completed);
4491 nodes[0].node = &nodes_0_deserialized;
4493 // After deserializing, make sure the funding_transaction is still held by the channel manager
4494 let events_4 = nodes[0].node.get_and_clear_pending_events();
4495 assert_eq!(events_4.len(), 0);
4496 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4497 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4499 // Make sure the channel is functioning as though the de/serialization never happened
4500 assert_eq!(nodes[0].node.list_channels().len(), 1);
4501 check_added_monitors!(nodes[0], 1);
4503 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4504 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4505 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4506 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4508 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4509 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4510 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4511 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4513 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4514 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4515 for node in nodes.iter() {
4516 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4517 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4518 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4521 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4525 fn test_simple_manager_serialize_deserialize() {
4526 let chanmon_cfgs = create_chanmon_cfgs(2);
4527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4529 let logger: test_utils::TestLogger;
4530 let fee_estimator: test_utils::TestFeeEstimator;
4531 let persister: test_utils::TestPersister;
4532 let new_chain_monitor: test_utils::TestChainMonitor;
4533 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4534 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4535 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4537 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4538 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4540 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4542 let nodes_0_serialized = nodes[0].node.encode();
4543 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4544 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4546 logger = test_utils::TestLogger::new();
4547 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4548 persister = test_utils::TestPersister::new();
4549 let keys_manager = &chanmon_cfgs[0].keys_manager;
4550 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4551 nodes[0].chain_monitor = &new_chain_monitor;
4552 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4553 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4554 &mut chan_0_monitor_read, keys_manager).unwrap();
4555 assert!(chan_0_monitor_read.is_empty());
4557 let mut nodes_0_read = &nodes_0_serialized[..];
4558 let (_, nodes_0_deserialized_tmp) = {
4559 let mut channel_monitors = HashMap::new();
4560 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4561 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4562 default_config: UserConfig::default(),
4564 fee_estimator: &fee_estimator,
4565 chain_monitor: nodes[0].chain_monitor,
4566 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4571 nodes_0_deserialized = nodes_0_deserialized_tmp;
4572 assert!(nodes_0_read.is_empty());
4574 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
4575 ChannelMonitorUpdateStatus::Completed);
4576 nodes[0].node = &nodes_0_deserialized;
4577 check_added_monitors!(nodes[0], 1);
4579 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4581 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4582 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4586 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4587 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4588 let chanmon_cfgs = create_chanmon_cfgs(4);
4589 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4590 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4591 let logger: test_utils::TestLogger;
4592 let fee_estimator: test_utils::TestFeeEstimator;
4593 let persister: test_utils::TestPersister;
4594 let new_chain_monitor: test_utils::TestChainMonitor;
4595 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4596 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4597 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4598 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
4599 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4601 let mut node_0_stale_monitors_serialized = Vec::new();
4602 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4603 let mut writer = test_utils::TestVecWriter(Vec::new());
4604 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4605 node_0_stale_monitors_serialized.push(writer.0);
4608 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4610 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4611 let nodes_0_serialized = nodes[0].node.encode();
4613 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4614 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4615 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4616 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4618 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4620 let mut node_0_monitors_serialized = Vec::new();
4621 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4622 let mut writer = test_utils::TestVecWriter(Vec::new());
4623 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4624 node_0_monitors_serialized.push(writer.0);
4627 logger = test_utils::TestLogger::new();
4628 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4629 persister = test_utils::TestPersister::new();
4630 let keys_manager = &chanmon_cfgs[0].keys_manager;
4631 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4632 nodes[0].chain_monitor = &new_chain_monitor;
4635 let mut node_0_stale_monitors = Vec::new();
4636 for serialized in node_0_stale_monitors_serialized.iter() {
4637 let mut read = &serialized[..];
4638 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4639 assert!(read.is_empty());
4640 node_0_stale_monitors.push(monitor);
4643 let mut node_0_monitors = Vec::new();
4644 for serialized in node_0_monitors_serialized.iter() {
4645 let mut read = &serialized[..];
4646 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4647 assert!(read.is_empty());
4648 node_0_monitors.push(monitor);
4651 let mut nodes_0_read = &nodes_0_serialized[..];
4652 if let Err(msgs::DecodeError::InvalidValue) =
4653 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4654 default_config: UserConfig::default(),
4656 fee_estimator: &fee_estimator,
4657 chain_monitor: nodes[0].chain_monitor,
4658 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4660 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4662 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4665 let mut nodes_0_read = &nodes_0_serialized[..];
4666 let (_, nodes_0_deserialized_tmp) =
4667 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4668 default_config: UserConfig::default(),
4670 fee_estimator: &fee_estimator,
4671 chain_monitor: nodes[0].chain_monitor,
4672 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4674 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4676 nodes_0_deserialized = nodes_0_deserialized_tmp;
4677 assert!(nodes_0_read.is_empty());
4679 { // Channel close should result in a commitment tx
4680 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4681 assert_eq!(txn.len(), 1);
4682 check_spends!(txn[0], funding_tx);
4683 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4686 for monitor in node_0_monitors.drain(..) {
4687 assert_eq!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
4688 ChannelMonitorUpdateStatus::Completed);
4689 check_added_monitors!(nodes[0], 1);
4691 nodes[0].node = &nodes_0_deserialized;
4692 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4694 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4695 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4696 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4697 //... and we can even still claim the payment!
4698 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4700 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4701 let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
4702 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
4703 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4704 let mut found_err = false;
4705 for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
4706 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
4708 &ErrorAction::SendErrorMessage { ref msg } => {
4709 assert_eq!(msg.channel_id, channel_id);
4710 assert!(!found_err);
4713 _ => panic!("Unexpected event!"),
4720 macro_rules! check_spendable_outputs {
4721 ($node: expr, $keysinterface: expr) => {
4723 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4724 let mut txn = Vec::new();
4725 let mut all_outputs = Vec::new();
4726 let secp_ctx = Secp256k1::new();
4727 for event in events.drain(..) {
4729 Event::SpendableOutputs { mut outputs } => {
4730 for outp in outputs.drain(..) {
4731 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4732 all_outputs.push(outp);
4735 _ => panic!("Unexpected event"),
4738 if all_outputs.len() > 1 {
4739 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) {
4749 fn test_claim_sizeable_push_msat() {
4750 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4751 let chanmon_cfgs = create_chanmon_cfgs(2);
4752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4754 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4756 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());
4757 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4758 check_closed_broadcast!(nodes[1], true);
4759 check_added_monitors!(nodes[1], 1);
4760 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4761 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4762 assert_eq!(node_txn.len(), 1);
4763 check_spends!(node_txn[0], chan.3);
4764 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
4766 mine_transaction(&nodes[1], &node_txn[0]);
4767 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4769 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4770 assert_eq!(spend_txn.len(), 1);
4771 assert_eq!(spend_txn[0].input.len(), 1);
4772 check_spends!(spend_txn[0], node_txn[0]);
4773 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4777 fn test_claim_on_remote_sizeable_push_msat() {
4778 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4779 // to_remote output is encumbered by a P2WPKH
4780 let chanmon_cfgs = create_chanmon_cfgs(2);
4781 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4782 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4783 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4785 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());
4786 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4787 check_closed_broadcast!(nodes[0], true);
4788 check_added_monitors!(nodes[0], 1);
4789 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4791 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4792 assert_eq!(node_txn.len(), 1);
4793 check_spends!(node_txn[0], chan.3);
4794 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
4796 mine_transaction(&nodes[1], &node_txn[0]);
4797 check_closed_broadcast!(nodes[1], true);
4798 check_added_monitors!(nodes[1], 1);
4799 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4800 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4802 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4803 assert_eq!(spend_txn.len(), 1);
4804 check_spends!(spend_txn[0], node_txn[0]);
4808 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4809 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4810 // to_remote output is encumbered by a P2WPKH
4812 let chanmon_cfgs = create_chanmon_cfgs(2);
4813 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4814 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4815 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4817 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4818 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4819 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4820 assert_eq!(revoked_local_txn[0].input.len(), 1);
4821 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4823 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4824 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4825 check_closed_broadcast!(nodes[1], true);
4826 check_added_monitors!(nodes[1], 1);
4827 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4829 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4830 mine_transaction(&nodes[1], &node_txn[0]);
4831 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4833 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4834 assert_eq!(spend_txn.len(), 3);
4835 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4836 check_spends!(spend_txn[1], node_txn[0]);
4837 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4841 fn test_static_spendable_outputs_preimage_tx() {
4842 let chanmon_cfgs = create_chanmon_cfgs(2);
4843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4845 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4847 // Create some initial channels
4848 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4850 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4852 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4853 assert_eq!(commitment_tx[0].input.len(), 1);
4854 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4856 // Settle A's commitment tx on B's chain
4857 nodes[1].node.claim_funds(payment_preimage);
4858 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4859 check_added_monitors!(nodes[1], 1);
4860 mine_transaction(&nodes[1], &commitment_tx[0]);
4861 check_added_monitors!(nodes[1], 1);
4862 let events = nodes[1].node.get_and_clear_pending_msg_events();
4864 MessageSendEvent::UpdateHTLCs { .. } => {},
4865 _ => panic!("Unexpected event"),
4868 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4869 _ => panic!("Unexepected event"),
4872 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4873 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4874 assert_eq!(node_txn.len(), 3);
4875 check_spends!(node_txn[0], commitment_tx[0]);
4876 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4877 check_spends!(node_txn[1], chan_1.3);
4878 check_spends!(node_txn[2], node_txn[1]);
4880 mine_transaction(&nodes[1], &node_txn[0]);
4881 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4882 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4884 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4885 assert_eq!(spend_txn.len(), 1);
4886 check_spends!(spend_txn[0], node_txn[0]);
4890 fn test_static_spendable_outputs_timeout_tx() {
4891 let chanmon_cfgs = create_chanmon_cfgs(2);
4892 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4893 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4894 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4896 // Create some initial channels
4897 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4899 // Rebalance the network a bit by relaying one payment through all the channels ...
4900 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4902 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4904 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4905 assert_eq!(commitment_tx[0].input.len(), 1);
4906 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4908 // Settle A's commitment tx on B' chain
4909 mine_transaction(&nodes[1], &commitment_tx[0]);
4910 check_added_monitors!(nodes[1], 1);
4911 let events = nodes[1].node.get_and_clear_pending_msg_events();
4913 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4914 _ => panic!("Unexpected event"),
4916 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4918 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4919 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4920 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4921 check_spends!(node_txn[0], chan_1.3.clone());
4922 check_spends!(node_txn[1], commitment_tx[0].clone());
4923 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4925 mine_transaction(&nodes[1], &node_txn[1]);
4926 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4927 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4928 expect_payment_failed!(nodes[1], our_payment_hash, false);
4930 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4931 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4932 check_spends!(spend_txn[0], commitment_tx[0]);
4933 check_spends!(spend_txn[1], node_txn[1]);
4934 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4938 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4939 let chanmon_cfgs = create_chanmon_cfgs(2);
4940 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4941 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4942 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4944 // Create some initial channels
4945 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4947 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4948 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4949 assert_eq!(revoked_local_txn[0].input.len(), 1);
4950 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4952 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4954 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4955 check_closed_broadcast!(nodes[1], true);
4956 check_added_monitors!(nodes[1], 1);
4957 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4959 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4960 assert_eq!(node_txn.len(), 2);
4961 assert_eq!(node_txn[0].input.len(), 2);
4962 check_spends!(node_txn[0], revoked_local_txn[0]);
4964 mine_transaction(&nodes[1], &node_txn[0]);
4965 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4967 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4968 assert_eq!(spend_txn.len(), 1);
4969 check_spends!(spend_txn[0], node_txn[0]);
4973 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4974 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4975 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4976 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4977 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4978 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4980 // Create some initial channels
4981 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4983 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4984 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4985 assert_eq!(revoked_local_txn[0].input.len(), 1);
4986 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4988 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4990 // A will generate HTLC-Timeout from revoked commitment tx
4991 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4992 check_closed_broadcast!(nodes[0], true);
4993 check_added_monitors!(nodes[0], 1);
4994 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4995 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4997 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4998 assert_eq!(revoked_htlc_txn.len(), 2);
4999 check_spends!(revoked_htlc_txn[0], chan_1.3);
5000 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5001 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5002 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5003 assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
5005 // B will generate justice tx from A's revoked commitment/HTLC tx
5006 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5007 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5008 check_closed_broadcast!(nodes[1], true);
5009 check_added_monitors!(nodes[1], 1);
5010 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5012 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5013 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5014 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5015 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5016 // transactions next...
5017 assert_eq!(node_txn[0].input.len(), 3);
5018 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5020 assert_eq!(node_txn[1].input.len(), 2);
5021 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5022 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5023 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5025 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5026 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5029 assert_eq!(node_txn[2].input.len(), 1);
5030 check_spends!(node_txn[2], chan_1.3);
5032 mine_transaction(&nodes[1], &node_txn[1]);
5033 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5035 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5036 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5037 assert_eq!(spend_txn.len(), 1);
5038 assert_eq!(spend_txn[0].input.len(), 1);
5039 check_spends!(spend_txn[0], node_txn[1]);
5043 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5044 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5045 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5046 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5047 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5048 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5050 // Create some initial channels
5051 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5053 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5054 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5055 assert_eq!(revoked_local_txn[0].input.len(), 1);
5056 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5058 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5059 assert_eq!(revoked_local_txn[0].output.len(), 2);
5061 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5063 // B will generate HTLC-Success from revoked commitment tx
5064 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5065 check_closed_broadcast!(nodes[1], true);
5066 check_added_monitors!(nodes[1], 1);
5067 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5068 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5070 assert_eq!(revoked_htlc_txn.len(), 2);
5071 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5072 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5073 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5075 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5076 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5077 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5079 // A will generate justice tx from B's revoked commitment/HTLC tx
5080 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5081 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5082 check_closed_broadcast!(nodes[0], true);
5083 check_added_monitors!(nodes[0], 1);
5084 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5086 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5087 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5089 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5090 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5091 // transactions next...
5092 assert_eq!(node_txn[0].input.len(), 2);
5093 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5094 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5095 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5097 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5098 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5101 assert_eq!(node_txn[1].input.len(), 1);
5102 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5104 check_spends!(node_txn[2], chan_1.3);
5106 mine_transaction(&nodes[0], &node_txn[1]);
5107 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5109 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5110 // didn't try to generate any new transactions.
5112 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5113 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5114 assert_eq!(spend_txn.len(), 3);
5115 assert_eq!(spend_txn[0].input.len(), 1);
5116 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5117 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5118 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5119 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5123 fn test_onchain_to_onchain_claim() {
5124 // Test that in case of channel closure, we detect the state of output and claim HTLC
5125 // on downstream peer's remote commitment tx.
5126 // First, have C claim an HTLC against its own latest commitment transaction.
5127 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5129 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5132 let chanmon_cfgs = create_chanmon_cfgs(3);
5133 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5134 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5135 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5137 // Create some initial channels
5138 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5139 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5141 // Ensure all nodes are at the same height
5142 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5143 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5144 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5145 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5147 // Rebalance the network a bit by relaying one payment through all the channels ...
5148 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5149 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5151 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5152 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5153 check_spends!(commitment_tx[0], chan_2.3);
5154 nodes[2].node.claim_funds(payment_preimage);
5155 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5156 check_added_monitors!(nodes[2], 1);
5157 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5158 assert!(updates.update_add_htlcs.is_empty());
5159 assert!(updates.update_fail_htlcs.is_empty());
5160 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5161 assert!(updates.update_fail_malformed_htlcs.is_empty());
5163 mine_transaction(&nodes[2], &commitment_tx[0]);
5164 check_closed_broadcast!(nodes[2], true);
5165 check_added_monitors!(nodes[2], 1);
5166 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5168 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5169 assert_eq!(c_txn.len(), 3);
5170 assert_eq!(c_txn[0], c_txn[2]);
5171 assert_eq!(commitment_tx[0], c_txn[1]);
5172 check_spends!(c_txn[1], chan_2.3);
5173 check_spends!(c_txn[2], c_txn[1]);
5174 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5175 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5176 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5177 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5179 // 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
5180 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5181 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5182 check_added_monitors!(nodes[1], 1);
5183 let events = nodes[1].node.get_and_clear_pending_events();
5184 assert_eq!(events.len(), 2);
5186 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5187 _ => panic!("Unexpected event"),
5190 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5191 assert_eq!(fee_earned_msat, Some(1000));
5192 assert_eq!(prev_channel_id, Some(chan_1.2));
5193 assert_eq!(claim_from_onchain_tx, true);
5194 assert_eq!(next_channel_id, Some(chan_2.2));
5196 _ => panic!("Unexpected event"),
5199 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5200 // ChannelMonitor: claim tx
5201 assert_eq!(b_txn.len(), 1);
5202 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5205 check_added_monitors!(nodes[1], 1);
5206 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5207 assert_eq!(msg_events.len(), 3);
5208 match msg_events[0] {
5209 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5210 _ => panic!("Unexpected event"),
5212 match msg_events[1] {
5213 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5214 _ => panic!("Unexpected event"),
5216 match msg_events[2] {
5217 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, .. } } => {
5218 assert!(update_add_htlcs.is_empty());
5219 assert!(update_fail_htlcs.is_empty());
5220 assert_eq!(update_fulfill_htlcs.len(), 1);
5221 assert!(update_fail_malformed_htlcs.is_empty());
5222 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5224 _ => panic!("Unexpected event"),
5226 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5227 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5228 mine_transaction(&nodes[1], &commitment_tx[0]);
5229 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5230 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5231 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5232 assert_eq!(b_txn.len(), 3);
5233 check_spends!(b_txn[1], chan_1.3);
5234 check_spends!(b_txn[2], b_txn[1]);
5235 check_spends!(b_txn[0], commitment_tx[0]);
5236 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5237 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5238 assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5240 check_closed_broadcast!(nodes[1], true);
5241 check_added_monitors!(nodes[1], 1);
5245 fn test_duplicate_payment_hash_one_failure_one_success() {
5246 // Topology : A --> B --> C --> D
5247 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5248 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5249 // we forward one of the payments onwards to D.
5250 let chanmon_cfgs = create_chanmon_cfgs(4);
5251 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5252 // When this test was written, the default base fee floated based on the HTLC count.
5253 // It is now fixed, so we simply set the fee to the expected value here.
5254 let mut config = test_default_channel_config();
5255 config.channel_config.forwarding_fee_base_msat = 196;
5256 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5257 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5258 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5260 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5261 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5262 create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5264 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5265 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5266 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5267 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5268 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5270 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5272 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5273 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5274 // script push size limit so that the below script length checks match
5275 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5276 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5277 .with_features(channelmanager::provided_invoice_features());
5278 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5279 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5281 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5282 assert_eq!(commitment_txn[0].input.len(), 1);
5283 check_spends!(commitment_txn[0], chan_2.3);
5285 mine_transaction(&nodes[1], &commitment_txn[0]);
5286 check_closed_broadcast!(nodes[1], true);
5287 check_added_monitors!(nodes[1], 1);
5288 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5289 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5291 let htlc_timeout_tx;
5292 { // Extract one of the two HTLC-Timeout transaction
5293 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5294 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5295 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5296 check_spends!(node_txn[0], chan_2.3);
5298 check_spends!(node_txn[1], commitment_txn[0]);
5299 assert_eq!(node_txn[1].input.len(), 1);
5301 if node_txn.len() > 3 {
5302 check_spends!(node_txn[2], commitment_txn[0]);
5303 assert_eq!(node_txn[2].input.len(), 1);
5304 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5306 check_spends!(node_txn[3], commitment_txn[0]);
5307 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5309 check_spends!(node_txn[2], commitment_txn[0]);
5310 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5313 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5314 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5315 if node_txn.len() > 3 {
5316 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5318 htlc_timeout_tx = node_txn[1].clone();
5321 nodes[2].node.claim_funds(our_payment_preimage);
5322 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5324 mine_transaction(&nodes[2], &commitment_txn[0]);
5325 check_added_monitors!(nodes[2], 2);
5326 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5327 let events = nodes[2].node.get_and_clear_pending_msg_events();
5329 MessageSendEvent::UpdateHTLCs { .. } => {},
5330 _ => panic!("Unexpected event"),
5333 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5334 _ => panic!("Unexepected event"),
5336 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5337 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)
5338 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5339 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5340 assert_eq!(htlc_success_txn[0].input.len(), 1);
5341 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5342 assert_eq!(htlc_success_txn[1].input.len(), 1);
5343 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5344 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5345 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5346 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5347 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5348 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5350 mine_transaction(&nodes[1], &htlc_timeout_tx);
5351 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5352 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 }]);
5353 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5354 assert!(htlc_updates.update_add_htlcs.is_empty());
5355 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5356 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5357 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5358 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5359 check_added_monitors!(nodes[1], 1);
5361 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5362 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5364 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5366 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5368 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5369 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5370 // and nodes[2] fee) is rounded down and then claimed in full.
5371 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5372 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5373 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5374 assert!(updates.update_add_htlcs.is_empty());
5375 assert!(updates.update_fail_htlcs.is_empty());
5376 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5377 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5378 assert!(updates.update_fail_malformed_htlcs.is_empty());
5379 check_added_monitors!(nodes[1], 1);
5381 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5382 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5384 let events = nodes[0].node.get_and_clear_pending_events();
5386 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5387 assert_eq!(*payment_preimage, our_payment_preimage);
5388 assert_eq!(*payment_hash, duplicate_payment_hash);
5390 _ => panic!("Unexpected event"),
5395 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5396 let chanmon_cfgs = create_chanmon_cfgs(2);
5397 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5399 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5401 // Create some initial channels
5402 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5404 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5405 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5406 assert_eq!(local_txn.len(), 1);
5407 assert_eq!(local_txn[0].input.len(), 1);
5408 check_spends!(local_txn[0], chan_1.3);
5410 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5411 nodes[1].node.claim_funds(payment_preimage);
5412 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5413 check_added_monitors!(nodes[1], 1);
5415 mine_transaction(&nodes[1], &local_txn[0]);
5416 check_added_monitors!(nodes[1], 1);
5417 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5418 let events = nodes[1].node.get_and_clear_pending_msg_events();
5420 MessageSendEvent::UpdateHTLCs { .. } => {},
5421 _ => panic!("Unexpected event"),
5424 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5425 _ => panic!("Unexepected event"),
5428 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5429 assert_eq!(node_txn.len(), 3);
5430 assert_eq!(node_txn[0], node_txn[2]);
5431 assert_eq!(node_txn[1], local_txn[0]);
5432 assert_eq!(node_txn[0].input.len(), 1);
5433 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5434 check_spends!(node_txn[0], local_txn[0]);
5438 mine_transaction(&nodes[1], &node_tx);
5439 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5441 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5442 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5443 assert_eq!(spend_txn.len(), 1);
5444 assert_eq!(spend_txn[0].input.len(), 1);
5445 check_spends!(spend_txn[0], node_tx);
5446 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5449 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5450 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5451 // unrevoked commitment transaction.
5452 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5453 // a remote RAA before they could be failed backwards (and combinations thereof).
5454 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5455 // use the same payment hashes.
5456 // Thus, we use a six-node network:
5461 // And test where C fails back to A/B when D announces its latest commitment transaction
5462 let chanmon_cfgs = create_chanmon_cfgs(6);
5463 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5464 // When this test was written, the default base fee floated based on the HTLC count.
5465 // It is now fixed, so we simply set the fee to the expected value here.
5466 let mut config = test_default_channel_config();
5467 config.channel_config.forwarding_fee_base_msat = 196;
5468 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5469 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5470 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5472 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5473 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5474 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5475 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5476 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5478 // Rebalance and check output sanity...
5479 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5480 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5481 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5483 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5485 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
5487 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
5488 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5490 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
5492 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
5494 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5496 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5497 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5499 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());
5501 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());
5504 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5506 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5507 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
5510 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
5512 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5513 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());
5515 // Double-check that six of the new HTLC were added
5516 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5517 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5518 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5519 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5521 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5522 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5523 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5524 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5525 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5526 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5527 check_added_monitors!(nodes[4], 0);
5529 let failed_destinations = vec![
5530 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5531 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5532 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5533 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5535 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5536 check_added_monitors!(nodes[4], 1);
5538 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5539 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5540 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5541 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5542 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5543 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5545 // Fail 3rd below-dust and 7th above-dust HTLCs
5546 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5547 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5548 check_added_monitors!(nodes[5], 0);
5550 let failed_destinations_2 = vec![
5551 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5552 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5554 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5555 check_added_monitors!(nodes[5], 1);
5557 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5558 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5559 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5560 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5562 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5564 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5565 let failed_destinations_3 = vec![
5566 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5567 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5568 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5569 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5570 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5571 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5573 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5574 check_added_monitors!(nodes[3], 1);
5575 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5576 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5577 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5578 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5579 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5580 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5581 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5582 if deliver_last_raa {
5583 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5585 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5588 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5589 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5590 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5591 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5593 // We now broadcast the latest commitment transaction, which *should* result in failures for
5594 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5595 // the non-broadcast above-dust HTLCs.
5597 // Alternatively, we may broadcast the previous commitment transaction, which should only
5598 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5599 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5601 if announce_latest {
5602 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5604 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5606 let events = nodes[2].node.get_and_clear_pending_events();
5607 let close_event = if deliver_last_raa {
5608 assert_eq!(events.len(), 2 + 6);
5609 events.last().clone().unwrap()
5611 assert_eq!(events.len(), 1);
5612 events.last().clone().unwrap()
5615 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5616 _ => panic!("Unexpected event"),
5619 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5620 check_closed_broadcast!(nodes[2], true);
5621 if deliver_last_raa {
5622 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5624 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();
5625 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5627 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5628 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5630 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5633 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5635 check_added_monitors!(nodes[2], 3);
5637 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5638 assert_eq!(cs_msgs.len(), 2);
5639 let mut a_done = false;
5640 for msg in cs_msgs {
5642 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5643 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5644 // should be failed-backwards here.
5645 let target = if *node_id == nodes[0].node.get_our_node_id() {
5646 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5647 for htlc in &updates.update_fail_htlcs {
5648 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 });
5650 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5655 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5656 for htlc in &updates.update_fail_htlcs {
5657 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5659 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5660 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5663 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5664 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5665 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5666 if announce_latest {
5667 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5668 if *node_id == nodes[0].node.get_our_node_id() {
5669 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5672 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5674 _ => panic!("Unexpected event"),
5678 let as_events = nodes[0].node.get_and_clear_pending_events();
5679 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5680 let mut as_failds = HashSet::new();
5681 let mut as_updates = 0;
5682 for event in as_events.iter() {
5683 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5684 assert!(as_failds.insert(*payment_hash));
5685 if *payment_hash != payment_hash_2 {
5686 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5688 assert!(!payment_failed_permanently);
5690 if network_update.is_some() {
5693 } else { panic!("Unexpected event"); }
5695 assert!(as_failds.contains(&payment_hash_1));
5696 assert!(as_failds.contains(&payment_hash_2));
5697 if announce_latest {
5698 assert!(as_failds.contains(&payment_hash_3));
5699 assert!(as_failds.contains(&payment_hash_5));
5701 assert!(as_failds.contains(&payment_hash_6));
5703 let bs_events = nodes[1].node.get_and_clear_pending_events();
5704 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5705 let mut bs_failds = HashSet::new();
5706 let mut bs_updates = 0;
5707 for event in bs_events.iter() {
5708 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5709 assert!(bs_failds.insert(*payment_hash));
5710 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5711 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5713 assert!(!payment_failed_permanently);
5715 if network_update.is_some() {
5718 } else { panic!("Unexpected event"); }
5720 assert!(bs_failds.contains(&payment_hash_1));
5721 assert!(bs_failds.contains(&payment_hash_2));
5722 if announce_latest {
5723 assert!(bs_failds.contains(&payment_hash_4));
5725 assert!(bs_failds.contains(&payment_hash_5));
5727 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5728 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5729 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5730 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5731 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5732 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5736 fn test_fail_backwards_latest_remote_announce_a() {
5737 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5741 fn test_fail_backwards_latest_remote_announce_b() {
5742 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5746 fn test_fail_backwards_previous_remote_announce() {
5747 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5748 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5749 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5753 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5754 let chanmon_cfgs = create_chanmon_cfgs(2);
5755 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5756 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5757 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5759 // Create some initial channels
5760 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5762 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5763 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5764 assert_eq!(local_txn[0].input.len(), 1);
5765 check_spends!(local_txn[0], chan_1.3);
5767 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5768 mine_transaction(&nodes[0], &local_txn[0]);
5769 check_closed_broadcast!(nodes[0], true);
5770 check_added_monitors!(nodes[0], 1);
5771 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5772 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5774 let htlc_timeout = {
5775 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5776 assert_eq!(node_txn.len(), 2);
5777 check_spends!(node_txn[0], chan_1.3);
5778 assert_eq!(node_txn[1].input.len(), 1);
5779 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5780 check_spends!(node_txn[1], local_txn[0]);
5784 mine_transaction(&nodes[0], &htlc_timeout);
5785 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5786 expect_payment_failed!(nodes[0], our_payment_hash, false);
5788 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5789 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5790 assert_eq!(spend_txn.len(), 3);
5791 check_spends!(spend_txn[0], local_txn[0]);
5792 assert_eq!(spend_txn[1].input.len(), 1);
5793 check_spends!(spend_txn[1], htlc_timeout);
5794 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5795 assert_eq!(spend_txn[2].input.len(), 2);
5796 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5797 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5798 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5802 fn test_key_derivation_params() {
5803 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5804 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5805 // let us re-derive the channel key set to then derive a delayed_payment_key.
5807 let chanmon_cfgs = create_chanmon_cfgs(3);
5809 // We manually create the node configuration to backup the seed.
5810 let seed = [42; 32];
5811 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5812 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);
5813 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5814 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() };
5815 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5816 node_cfgs.remove(0);
5817 node_cfgs.insert(0, node);
5819 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5820 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5822 // Create some initial channels
5823 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5825 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5826 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5827 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5829 // Ensure all nodes are at the same height
5830 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5831 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5832 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5833 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5835 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5836 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5837 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5838 assert_eq!(local_txn_1[0].input.len(), 1);
5839 check_spends!(local_txn_1[0], chan_1.3);
5841 // We check funding pubkey are unique
5842 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]));
5843 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]));
5844 if from_0_funding_key_0 == from_1_funding_key_0
5845 || from_0_funding_key_0 == from_1_funding_key_1
5846 || from_0_funding_key_1 == from_1_funding_key_0
5847 || from_0_funding_key_1 == from_1_funding_key_1 {
5848 panic!("Funding pubkeys aren't unique");
5851 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5852 mine_transaction(&nodes[0], &local_txn_1[0]);
5853 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5854 check_closed_broadcast!(nodes[0], true);
5855 check_added_monitors!(nodes[0], 1);
5856 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5858 let htlc_timeout = {
5859 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5860 assert_eq!(node_txn[1].input.len(), 1);
5861 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5862 check_spends!(node_txn[1], local_txn_1[0]);
5866 mine_transaction(&nodes[0], &htlc_timeout);
5867 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5868 expect_payment_failed!(nodes[0], our_payment_hash, false);
5870 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5871 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5872 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5873 assert_eq!(spend_txn.len(), 3);
5874 check_spends!(spend_txn[0], local_txn_1[0]);
5875 assert_eq!(spend_txn[1].input.len(), 1);
5876 check_spends!(spend_txn[1], htlc_timeout);
5877 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5878 assert_eq!(spend_txn[2].input.len(), 2);
5879 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5880 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5881 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5885 fn test_static_output_closing_tx() {
5886 let chanmon_cfgs = create_chanmon_cfgs(2);
5887 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5888 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5889 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5891 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5893 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5894 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5896 mine_transaction(&nodes[0], &closing_tx);
5897 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5898 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5900 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5901 assert_eq!(spend_txn.len(), 1);
5902 check_spends!(spend_txn[0], closing_tx);
5904 mine_transaction(&nodes[1], &closing_tx);
5905 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5906 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5908 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5909 assert_eq!(spend_txn.len(), 1);
5910 check_spends!(spend_txn[0], closing_tx);
5913 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5914 let chanmon_cfgs = create_chanmon_cfgs(2);
5915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5916 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5917 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5918 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5920 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5922 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5923 // present in B's local commitment transaction, but none of A's commitment transactions.
5924 nodes[1].node.claim_funds(payment_preimage);
5925 check_added_monitors!(nodes[1], 1);
5926 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5928 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5929 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5930 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5932 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5933 check_added_monitors!(nodes[0], 1);
5934 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5935 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5936 check_added_monitors!(nodes[1], 1);
5938 let starting_block = nodes[1].best_block_info();
5939 let mut block = Block {
5940 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5943 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5944 connect_block(&nodes[1], &block);
5945 block.header.prev_blockhash = block.block_hash();
5947 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5948 check_closed_broadcast!(nodes[1], true);
5949 check_added_monitors!(nodes[1], 1);
5950 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5953 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5954 let chanmon_cfgs = create_chanmon_cfgs(2);
5955 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5956 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5957 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5958 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5960 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5961 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5962 check_added_monitors!(nodes[0], 1);
5964 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5966 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5967 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5968 // to "time out" the HTLC.
5970 let starting_block = nodes[1].best_block_info();
5971 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5973 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5974 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5975 header.prev_blockhash = header.block_hash();
5977 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5978 check_closed_broadcast!(nodes[0], true);
5979 check_added_monitors!(nodes[0], 1);
5980 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5983 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5984 let chanmon_cfgs = create_chanmon_cfgs(3);
5985 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5986 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5987 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5988 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5990 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5991 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5992 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5993 // actually revoked.
5994 let htlc_value = if use_dust { 50000 } else { 3000000 };
5995 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5996 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5997 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5998 check_added_monitors!(nodes[1], 1);
6000 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6001 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6002 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6003 check_added_monitors!(nodes[0], 1);
6004 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6005 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6006 check_added_monitors!(nodes[1], 1);
6007 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6008 check_added_monitors!(nodes[1], 1);
6009 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6011 if check_revoke_no_close {
6012 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6013 check_added_monitors!(nodes[0], 1);
6016 let starting_block = nodes[1].best_block_info();
6017 let mut block = Block {
6018 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
6021 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6022 connect_block(&nodes[0], &block);
6023 block.header.prev_blockhash = block.block_hash();
6025 if !check_revoke_no_close {
6026 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6027 check_closed_broadcast!(nodes[0], true);
6028 check_added_monitors!(nodes[0], 1);
6029 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6031 let events = nodes[0].node.get_and_clear_pending_events();
6032 assert_eq!(events.len(), 2);
6033 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6034 assert_eq!(*payment_hash, our_payment_hash);
6035 } else { panic!("Unexpected event"); }
6036 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6037 assert_eq!(*payment_hash, our_payment_hash);
6038 } else { panic!("Unexpected event"); }
6042 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6043 // There are only a few cases to test here:
6044 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6045 // broadcastable commitment transactions result in channel closure,
6046 // * its included in an unrevoked-but-previous remote commitment transaction,
6047 // * its included in the latest remote or local commitment transactions.
6048 // We test each of the three possible commitment transactions individually and use both dust and
6050 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6051 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6052 // tested for at least one of the cases in other tests.
6054 fn htlc_claim_single_commitment_only_a() {
6055 do_htlc_claim_local_commitment_only(true);
6056 do_htlc_claim_local_commitment_only(false);
6058 do_htlc_claim_current_remote_commitment_only(true);
6059 do_htlc_claim_current_remote_commitment_only(false);
6063 fn htlc_claim_single_commitment_only_b() {
6064 do_htlc_claim_previous_remote_commitment_only(true, false);
6065 do_htlc_claim_previous_remote_commitment_only(false, false);
6066 do_htlc_claim_previous_remote_commitment_only(true, true);
6067 do_htlc_claim_previous_remote_commitment_only(false, true);
6072 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6073 let chanmon_cfgs = create_chanmon_cfgs(2);
6074 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6075 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6076 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6077 // Force duplicate randomness for every get-random call
6078 for node in nodes.iter() {
6079 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6082 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6083 let channel_value_satoshis=10000;
6084 let push_msat=10001;
6085 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6086 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6087 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6088 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6090 // Create a second channel with the same random values. This used to panic due to a colliding
6091 // channel_id, but now panics due to a colliding outbound SCID alias.
6092 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6096 fn bolt2_open_channel_sending_node_checks_part2() {
6097 let chanmon_cfgs = create_chanmon_cfgs(2);
6098 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6099 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6100 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6102 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6103 let channel_value_satoshis=2^24;
6104 let push_msat=10001;
6105 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6107 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6108 let channel_value_satoshis=10000;
6109 // Test when push_msat is equal to 1000 * funding_satoshis.
6110 let push_msat=1000*channel_value_satoshis+1;
6111 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6113 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6114 let channel_value_satoshis=10000;
6115 let push_msat=10001;
6116 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
6117 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6118 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6120 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6121 // 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
6122 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6124 // 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.
6125 assert!(BREAKDOWN_TIMEOUT>0);
6126 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6128 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6129 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6130 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6132 // 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.
6133 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6134 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6135 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6136 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6137 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6141 fn bolt2_open_channel_sane_dust_limit() {
6142 let chanmon_cfgs = create_chanmon_cfgs(2);
6143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6145 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6147 let channel_value_satoshis=1000000;
6148 let push_msat=10001;
6149 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6150 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6151 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6152 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6154 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
6155 let events = nodes[1].node.get_and_clear_pending_msg_events();
6156 let err_msg = match events[0] {
6157 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6160 _ => panic!("Unexpected event"),
6162 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6165 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6166 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6167 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6168 // is no longer affordable once it's freed.
6170 fn test_fail_holding_cell_htlc_upon_free() {
6171 let chanmon_cfgs = create_chanmon_cfgs(2);
6172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6174 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6175 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6177 // First nodes[0] generates an update_fee, setting the channel's
6178 // pending_update_fee.
6180 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6181 *feerate_lock += 20;
6183 nodes[0].node.timer_tick_occurred();
6184 check_added_monitors!(nodes[0], 1);
6186 let events = nodes[0].node.get_and_clear_pending_msg_events();
6187 assert_eq!(events.len(), 1);
6188 let (update_msg, commitment_signed) = match events[0] {
6189 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6190 (update_fee.as_ref(), commitment_signed)
6192 _ => panic!("Unexpected event"),
6195 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6197 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6198 let channel_reserve = chan_stat.channel_reserve_msat;
6199 let feerate = get_feerate!(nodes[0], chan.2);
6200 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6202 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6203 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6204 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6206 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6207 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6208 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6209 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6211 // Flush the pending fee update.
6212 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6213 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6214 check_added_monitors!(nodes[1], 1);
6215 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6216 check_added_monitors!(nodes[0], 1);
6218 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6219 // HTLC, but now that the fee has been raised the payment will now fail, causing
6220 // us to surface its failure to the user.
6221 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6222 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6223 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);
6224 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 {}",
6225 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6226 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6228 // Check that the payment failed to be sent out.
6229 let events = nodes[0].node.get_and_clear_pending_events();
6230 assert_eq!(events.len(), 1);
6232 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6233 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6234 assert_eq!(our_payment_hash.clone(), *payment_hash);
6235 assert_eq!(*payment_failed_permanently, false);
6236 assert_eq!(*all_paths_failed, true);
6237 assert_eq!(*network_update, None);
6238 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
6240 _ => panic!("Unexpected event"),
6244 // Test that if multiple HTLCs are released from the holding cell and one is
6245 // valid but the other is no longer valid upon release, the valid HTLC can be
6246 // successfully completed while the other one fails as expected.
6248 fn test_free_and_fail_holding_cell_htlcs() {
6249 let chanmon_cfgs = create_chanmon_cfgs(2);
6250 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6251 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6252 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6253 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6255 // First nodes[0] generates an update_fee, setting the channel's
6256 // pending_update_fee.
6258 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6259 *feerate_lock += 200;
6261 nodes[0].node.timer_tick_occurred();
6262 check_added_monitors!(nodes[0], 1);
6264 let events = nodes[0].node.get_and_clear_pending_msg_events();
6265 assert_eq!(events.len(), 1);
6266 let (update_msg, commitment_signed) = match events[0] {
6267 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6268 (update_fee.as_ref(), commitment_signed)
6270 _ => panic!("Unexpected event"),
6273 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6275 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6276 let channel_reserve = chan_stat.channel_reserve_msat;
6277 let feerate = get_feerate!(nodes[0], chan.2);
6278 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6280 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6282 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6283 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6284 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6286 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6287 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6288 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6289 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6290 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6291 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6292 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6294 // Flush the pending fee update.
6295 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6296 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6297 check_added_monitors!(nodes[1], 1);
6298 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6299 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6300 check_added_monitors!(nodes[0], 2);
6302 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6303 // but now that the fee has been raised the second payment will now fail, causing us
6304 // to surface its failure to the user. The first payment should succeed.
6305 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6306 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6307 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);
6308 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 {}",
6309 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6310 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6312 // Check that the second payment failed to be sent out.
6313 let events = nodes[0].node.get_and_clear_pending_events();
6314 assert_eq!(events.len(), 1);
6316 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6317 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6318 assert_eq!(payment_hash_2.clone(), *payment_hash);
6319 assert_eq!(*payment_failed_permanently, false);
6320 assert_eq!(*all_paths_failed, true);
6321 assert_eq!(*network_update, None);
6322 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
6324 _ => panic!("Unexpected event"),
6327 // Complete the first payment and the RAA from the fee update.
6328 let (payment_event, send_raa_event) = {
6329 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6330 assert_eq!(msgs.len(), 2);
6331 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6333 let raa = match send_raa_event {
6334 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6335 _ => panic!("Unexpected event"),
6337 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6338 check_added_monitors!(nodes[1], 1);
6339 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6340 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6341 let events = nodes[1].node.get_and_clear_pending_events();
6342 assert_eq!(events.len(), 1);
6344 Event::PendingHTLCsForwardable { .. } => {},
6345 _ => panic!("Unexpected event"),
6347 nodes[1].node.process_pending_htlc_forwards();
6348 let events = nodes[1].node.get_and_clear_pending_events();
6349 assert_eq!(events.len(), 1);
6351 Event::PaymentReceived { .. } => {},
6352 _ => panic!("Unexpected event"),
6354 nodes[1].node.claim_funds(payment_preimage_1);
6355 check_added_monitors!(nodes[1], 1);
6356 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6358 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6359 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6360 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6361 expect_payment_sent!(nodes[0], payment_preimage_1);
6364 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6365 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6366 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6369 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6370 let chanmon_cfgs = create_chanmon_cfgs(3);
6371 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6372 // When this test was written, the default base fee floated based on the HTLC count.
6373 // It is now fixed, so we simply set the fee to the expected value here.
6374 let mut config = test_default_channel_config();
6375 config.channel_config.forwarding_fee_base_msat = 196;
6376 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6377 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6378 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6379 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6381 // First nodes[1] generates an update_fee, setting the channel's
6382 // pending_update_fee.
6384 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6385 *feerate_lock += 20;
6387 nodes[1].node.timer_tick_occurred();
6388 check_added_monitors!(nodes[1], 1);
6390 let events = nodes[1].node.get_and_clear_pending_msg_events();
6391 assert_eq!(events.len(), 1);
6392 let (update_msg, commitment_signed) = match events[0] {
6393 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6394 (update_fee.as_ref(), commitment_signed)
6396 _ => panic!("Unexpected event"),
6399 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6401 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6402 let channel_reserve = chan_stat.channel_reserve_msat;
6403 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6404 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6406 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6408 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6409 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6410 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6411 let payment_event = {
6412 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6413 check_added_monitors!(nodes[0], 1);
6415 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6416 assert_eq!(events.len(), 1);
6418 SendEvent::from_event(events.remove(0))
6420 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6421 check_added_monitors!(nodes[1], 0);
6422 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6423 expect_pending_htlcs_forwardable!(nodes[1]);
6425 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6426 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6428 // Flush the pending fee update.
6429 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6430 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6431 check_added_monitors!(nodes[2], 1);
6432 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6433 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6434 check_added_monitors!(nodes[1], 2);
6436 // A final RAA message is generated to finalize the fee update.
6437 let events = nodes[1].node.get_and_clear_pending_msg_events();
6438 assert_eq!(events.len(), 1);
6440 let raa_msg = match &events[0] {
6441 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6444 _ => panic!("Unexpected event"),
6447 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6448 check_added_monitors!(nodes[2], 1);
6449 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6451 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6452 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6453 assert_eq!(process_htlc_forwards_event.len(), 2);
6454 match &process_htlc_forwards_event[0] {
6455 &Event::PendingHTLCsForwardable { .. } => {},
6456 _ => panic!("Unexpected event"),
6459 // In response, we call ChannelManager's process_pending_htlc_forwards
6460 nodes[1].node.process_pending_htlc_forwards();
6461 check_added_monitors!(nodes[1], 1);
6463 // This causes the HTLC to be failed backwards.
6464 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6465 assert_eq!(fail_event.len(), 1);
6466 let (fail_msg, commitment_signed) = match &fail_event[0] {
6467 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6468 assert_eq!(updates.update_add_htlcs.len(), 0);
6469 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6470 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6471 assert_eq!(updates.update_fail_htlcs.len(), 1);
6472 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6474 _ => panic!("Unexpected event"),
6477 // Pass the failure messages back to nodes[0].
6478 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6479 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6481 // Complete the HTLC failure+removal process.
6482 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6483 check_added_monitors!(nodes[0], 1);
6484 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6485 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6486 check_added_monitors!(nodes[1], 2);
6487 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6488 assert_eq!(final_raa_event.len(), 1);
6489 let raa = match &final_raa_event[0] {
6490 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6491 _ => panic!("Unexpected event"),
6493 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6494 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6495 check_added_monitors!(nodes[0], 1);
6498 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6499 // 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.
6500 //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.
6503 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6504 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6505 let chanmon_cfgs = create_chanmon_cfgs(2);
6506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6508 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6509 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6511 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6512 route.paths[0][0].fee_msat = 100;
6514 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6515 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6516 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6517 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6521 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6522 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6523 let chanmon_cfgs = create_chanmon_cfgs(2);
6524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6526 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6527 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6529 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6530 route.paths[0][0].fee_msat = 0;
6531 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6532 assert_eq!(err, "Cannot send 0-msat HTLC"));
6534 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6535 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6539 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6540 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6541 let chanmon_cfgs = create_chanmon_cfgs(2);
6542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6544 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6545 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6547 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6548 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6549 check_added_monitors!(nodes[0], 1);
6550 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6551 updates.update_add_htlcs[0].amount_msat = 0;
6553 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6554 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6555 check_closed_broadcast!(nodes[1], true).unwrap();
6556 check_added_monitors!(nodes[1], 1);
6557 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6561 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6562 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6563 //It is enforced when constructing a route.
6564 let chanmon_cfgs = create_chanmon_cfgs(2);
6565 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6566 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6567 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6568 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6570 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6571 .with_features(channelmanager::provided_invoice_features());
6572 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6573 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6574 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6575 assert_eq!(err, &"Channel CLTV overflowed?"));
6579 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6580 //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.
6581 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6582 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6583 let chanmon_cfgs = create_chanmon_cfgs(2);
6584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6586 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6587 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6588 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6590 for i in 0..max_accepted_htlcs {
6591 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6592 let payment_event = {
6593 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6594 check_added_monitors!(nodes[0], 1);
6596 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6597 assert_eq!(events.len(), 1);
6598 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6599 assert_eq!(htlcs[0].htlc_id, i);
6603 SendEvent::from_event(events.remove(0))
6605 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6606 check_added_monitors!(nodes[1], 0);
6607 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6609 expect_pending_htlcs_forwardable!(nodes[1]);
6610 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6612 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6613 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6614 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6616 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6617 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6621 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6622 //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.
6623 let chanmon_cfgs = create_chanmon_cfgs(2);
6624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6626 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6627 let channel_value = 100000;
6628 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6629 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6631 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6633 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6634 // Manually create a route over our max in flight (which our router normally automatically
6636 route.paths[0][0].fee_msat = max_in_flight + 1;
6637 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6638 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)));
6640 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6641 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);
6643 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6646 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6648 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6649 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6650 let chanmon_cfgs = create_chanmon_cfgs(2);
6651 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6652 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6653 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6654 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6655 let htlc_minimum_msat: u64;
6657 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6658 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6659 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6662 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6663 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6664 check_added_monitors!(nodes[0], 1);
6665 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6666 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6667 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6668 assert!(nodes[1].node.list_channels().is_empty());
6669 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6670 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()));
6671 check_added_monitors!(nodes[1], 1);
6672 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6676 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6677 //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
6678 let chanmon_cfgs = create_chanmon_cfgs(2);
6679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6681 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6682 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6684 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6685 let channel_reserve = chan_stat.channel_reserve_msat;
6686 let feerate = get_feerate!(nodes[0], chan.2);
6687 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6688 // The 2* and +1 are for the fee spike reserve.
6689 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6691 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6692 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6693 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6694 check_added_monitors!(nodes[0], 1);
6695 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6697 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6698 // at this time channel-initiatee receivers are not required to enforce that senders
6699 // respect the fee_spike_reserve.
6700 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6701 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6703 assert!(nodes[1].node.list_channels().is_empty());
6704 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6705 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6706 check_added_monitors!(nodes[1], 1);
6707 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6711 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6712 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6713 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6714 let chanmon_cfgs = create_chanmon_cfgs(2);
6715 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6716 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6717 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6718 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6720 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6721 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6722 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6723 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6724 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6725 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6727 let mut msg = msgs::UpdateAddHTLC {
6731 payment_hash: our_payment_hash,
6732 cltv_expiry: htlc_cltv,
6733 onion_routing_packet: onion_packet.clone(),
6736 for i in 0..super::channel::OUR_MAX_HTLCS {
6737 msg.htlc_id = i as u64;
6738 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6740 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6741 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6743 assert!(nodes[1].node.list_channels().is_empty());
6744 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6745 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6746 check_added_monitors!(nodes[1], 1);
6747 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6751 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6752 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6753 let chanmon_cfgs = create_chanmon_cfgs(2);
6754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6756 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6757 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6759 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6760 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6761 check_added_monitors!(nodes[0], 1);
6762 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6763 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6764 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6766 assert!(nodes[1].node.list_channels().is_empty());
6767 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6768 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6769 check_added_monitors!(nodes[1], 1);
6770 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6774 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6775 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6776 let chanmon_cfgs = create_chanmon_cfgs(2);
6777 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6778 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6779 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6781 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6782 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6783 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6784 check_added_monitors!(nodes[0], 1);
6785 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6786 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6787 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6789 assert!(nodes[1].node.list_channels().is_empty());
6790 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6791 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6792 check_added_monitors!(nodes[1], 1);
6793 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6797 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6798 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6799 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6800 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6801 let chanmon_cfgs = create_chanmon_cfgs(2);
6802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6804 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6806 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6807 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6808 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6809 check_added_monitors!(nodes[0], 1);
6810 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6811 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6813 //Disconnect and Reconnect
6814 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6815 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6816 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6817 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6818 assert_eq!(reestablish_1.len(), 1);
6819 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6820 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6821 assert_eq!(reestablish_2.len(), 1);
6822 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6823 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6824 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6825 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6828 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6829 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6830 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6831 check_added_monitors!(nodes[1], 1);
6832 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6834 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6836 assert!(nodes[1].node.list_channels().is_empty());
6837 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6838 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6839 check_added_monitors!(nodes[1], 1);
6840 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6844 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6845 //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.
6847 let chanmon_cfgs = create_chanmon_cfgs(2);
6848 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6849 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6850 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6851 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6852 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6853 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6855 check_added_monitors!(nodes[0], 1);
6856 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6857 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6859 let update_msg = msgs::UpdateFulfillHTLC{
6862 payment_preimage: our_payment_preimage,
6865 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6867 assert!(nodes[0].node.list_channels().is_empty());
6868 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6869 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()));
6870 check_added_monitors!(nodes[0], 1);
6871 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6875 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6876 //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.
6878 let chanmon_cfgs = create_chanmon_cfgs(2);
6879 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6880 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6881 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6882 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6884 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6885 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6886 check_added_monitors!(nodes[0], 1);
6887 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6888 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6890 let update_msg = msgs::UpdateFailHTLC{
6893 reason: msgs::OnionErrorPacket { data: Vec::new()},
6896 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6898 assert!(nodes[0].node.list_channels().is_empty());
6899 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6900 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()));
6901 check_added_monitors!(nodes[0], 1);
6902 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6906 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6907 //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.
6909 let chanmon_cfgs = create_chanmon_cfgs(2);
6910 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6911 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6912 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6913 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6915 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6916 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6917 check_added_monitors!(nodes[0], 1);
6918 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6920 let update_msg = msgs::UpdateFailMalformedHTLC{
6923 sha256_of_onion: [1; 32],
6924 failure_code: 0x8000,
6927 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6929 assert!(nodes[0].node.list_channels().is_empty());
6930 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6931 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()));
6932 check_added_monitors!(nodes[0], 1);
6933 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6937 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6938 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6940 let chanmon_cfgs = create_chanmon_cfgs(2);
6941 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6942 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6943 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6944 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6946 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6948 nodes[1].node.claim_funds(our_payment_preimage);
6949 check_added_monitors!(nodes[1], 1);
6950 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6952 let events = nodes[1].node.get_and_clear_pending_msg_events();
6953 assert_eq!(events.len(), 1);
6954 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6956 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, .. } } => {
6957 assert!(update_add_htlcs.is_empty());
6958 assert_eq!(update_fulfill_htlcs.len(), 1);
6959 assert!(update_fail_htlcs.is_empty());
6960 assert!(update_fail_malformed_htlcs.is_empty());
6961 assert!(update_fee.is_none());
6962 update_fulfill_htlcs[0].clone()
6964 _ => panic!("Unexpected event"),
6968 update_fulfill_msg.htlc_id = 1;
6970 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6972 assert!(nodes[0].node.list_channels().is_empty());
6973 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6974 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6975 check_added_monitors!(nodes[0], 1);
6976 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6980 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6981 //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.
6983 let chanmon_cfgs = create_chanmon_cfgs(2);
6984 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6985 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6986 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6987 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6989 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6991 nodes[1].node.claim_funds(our_payment_preimage);
6992 check_added_monitors!(nodes[1], 1);
6993 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6995 let events = nodes[1].node.get_and_clear_pending_msg_events();
6996 assert_eq!(events.len(), 1);
6997 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6999 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, .. } } => {
7000 assert!(update_add_htlcs.is_empty());
7001 assert_eq!(update_fulfill_htlcs.len(), 1);
7002 assert!(update_fail_htlcs.is_empty());
7003 assert!(update_fail_malformed_htlcs.is_empty());
7004 assert!(update_fee.is_none());
7005 update_fulfill_htlcs[0].clone()
7007 _ => panic!("Unexpected event"),
7011 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7013 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7015 assert!(nodes[0].node.list_channels().is_empty());
7016 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7017 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7018 check_added_monitors!(nodes[0], 1);
7019 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7023 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7024 //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.
7026 let chanmon_cfgs = create_chanmon_cfgs(2);
7027 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7028 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7029 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7030 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7032 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7033 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7034 check_added_monitors!(nodes[0], 1);
7036 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7037 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7039 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7040 check_added_monitors!(nodes[1], 0);
7041 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7043 let events = nodes[1].node.get_and_clear_pending_msg_events();
7045 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7047 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, .. } } => {
7048 assert!(update_add_htlcs.is_empty());
7049 assert!(update_fulfill_htlcs.is_empty());
7050 assert!(update_fail_htlcs.is_empty());
7051 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7052 assert!(update_fee.is_none());
7053 update_fail_malformed_htlcs[0].clone()
7055 _ => panic!("Unexpected event"),
7058 update_msg.failure_code &= !0x8000;
7059 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7061 assert!(nodes[0].node.list_channels().is_empty());
7062 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7063 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7064 check_added_monitors!(nodes[0], 1);
7065 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7069 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7070 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7071 // * 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.
7073 let chanmon_cfgs = create_chanmon_cfgs(3);
7074 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7075 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7076 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7077 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7078 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7080 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7083 let mut payment_event = {
7084 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7085 check_added_monitors!(nodes[0], 1);
7086 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7087 assert_eq!(events.len(), 1);
7088 SendEvent::from_event(events.remove(0))
7090 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7091 check_added_monitors!(nodes[1], 0);
7092 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7093 expect_pending_htlcs_forwardable!(nodes[1]);
7094 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7095 assert_eq!(events_2.len(), 1);
7096 check_added_monitors!(nodes[1], 1);
7097 payment_event = SendEvent::from_event(events_2.remove(0));
7098 assert_eq!(payment_event.msgs.len(), 1);
7101 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7102 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7103 check_added_monitors!(nodes[2], 0);
7104 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7106 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7107 assert_eq!(events_3.len(), 1);
7108 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7110 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 } } => {
7111 assert!(update_add_htlcs.is_empty());
7112 assert!(update_fulfill_htlcs.is_empty());
7113 assert!(update_fail_htlcs.is_empty());
7114 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7115 assert!(update_fee.is_none());
7116 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7118 _ => panic!("Unexpected event"),
7122 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7124 check_added_monitors!(nodes[1], 0);
7125 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7126 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 }]);
7127 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7128 assert_eq!(events_4.len(), 1);
7130 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7132 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, .. } } => {
7133 assert!(update_add_htlcs.is_empty());
7134 assert!(update_fulfill_htlcs.is_empty());
7135 assert_eq!(update_fail_htlcs.len(), 1);
7136 assert!(update_fail_malformed_htlcs.is_empty());
7137 assert!(update_fee.is_none());
7139 _ => panic!("Unexpected event"),
7142 check_added_monitors!(nodes[1], 1);
7146 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
7147 let chanmon_cfgs = create_chanmon_cfgs(3);
7148 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7149 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7150 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7151 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7152 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7154 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
7157 let mut payment_event = {
7158 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7159 check_added_monitors!(nodes[0], 1);
7160 SendEvent::from_node(&nodes[0])
7163 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7164 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7165 expect_pending_htlcs_forwardable!(nodes[1]);
7166 check_added_monitors!(nodes[1], 1);
7167 payment_event = SendEvent::from_node(&nodes[1]);
7168 assert_eq!(payment_event.msgs.len(), 1);
7171 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
7172 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7173 check_added_monitors!(nodes[2], 0);
7174 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7176 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7177 assert_eq!(events_3.len(), 1);
7179 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7180 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7181 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7182 update_msg.failure_code |= 0x2000;
7184 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7185 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7187 _ => panic!("Unexpected event"),
7190 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7191 vec![HTLCDestination::NextHopChannel {
7192 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7193 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7194 assert_eq!(events_4.len(), 1);
7195 check_added_monitors!(nodes[1], 1);
7198 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7199 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7200 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7202 _ => panic!("Unexpected event"),
7205 let events_5 = nodes[0].node.get_and_clear_pending_events();
7206 assert_eq!(events_5.len(), 1);
7208 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7209 // the node originating the error to its next hop.
7211 Event::PaymentPathFailed { network_update:
7212 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
7214 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7215 assert!(is_permanent);
7216 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7218 _ => panic!("Unexpected event"),
7221 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7224 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7225 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7226 // 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
7227 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7229 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7230 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7233 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7234 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7236 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7238 // We route 2 dust-HTLCs between A and B
7239 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7240 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7241 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7243 // Cache one local commitment tx as previous
7244 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7246 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7247 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7248 check_added_monitors!(nodes[1], 0);
7249 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7250 check_added_monitors!(nodes[1], 1);
7252 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7253 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7254 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7255 check_added_monitors!(nodes[0], 1);
7257 // Cache one local commitment tx as lastest
7258 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7260 let events = nodes[0].node.get_and_clear_pending_msg_events();
7262 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7263 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7265 _ => panic!("Unexpected event"),
7268 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7269 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7271 _ => panic!("Unexpected event"),
7274 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7275 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7276 if announce_latest {
7277 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7279 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7282 check_closed_broadcast!(nodes[0], true);
7283 check_added_monitors!(nodes[0], 1);
7284 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7286 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7287 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7288 let events = nodes[0].node.get_and_clear_pending_events();
7289 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7290 assert_eq!(events.len(), 2);
7291 let mut first_failed = false;
7292 for event in events {
7294 Event::PaymentPathFailed { payment_hash, .. } => {
7295 if payment_hash == payment_hash_1 {
7296 assert!(!first_failed);
7297 first_failed = true;
7299 assert_eq!(payment_hash, payment_hash_2);
7302 _ => panic!("Unexpected event"),
7308 fn test_failure_delay_dust_htlc_local_commitment() {
7309 do_test_failure_delay_dust_htlc_local_commitment(true);
7310 do_test_failure_delay_dust_htlc_local_commitment(false);
7313 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7314 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7315 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7316 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7317 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7318 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7319 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7321 let chanmon_cfgs = create_chanmon_cfgs(3);
7322 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7323 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7324 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7325 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7327 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7329 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7330 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7332 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7333 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7335 // We revoked bs_commitment_tx
7337 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7338 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7341 let mut timeout_tx = Vec::new();
7343 // We fail dust-HTLC 1 by broadcast of local commitment tx
7344 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7345 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7346 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7347 expect_payment_failed!(nodes[0], dust_hash, false);
7349 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7350 check_closed_broadcast!(nodes[0], true);
7351 check_added_monitors!(nodes[0], 1);
7352 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7353 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7354 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7355 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7356 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7357 mine_transaction(&nodes[0], &timeout_tx[0]);
7358 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7359 expect_payment_failed!(nodes[0], non_dust_hash, false);
7361 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7362 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7363 check_closed_broadcast!(nodes[0], true);
7364 check_added_monitors!(nodes[0], 1);
7365 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7366 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7368 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7369 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7370 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7371 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7372 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7373 // dust HTLC should have been failed.
7374 expect_payment_failed!(nodes[0], dust_hash, false);
7377 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7379 assert_eq!(timeout_tx[0].lock_time.0, 0);
7381 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7382 mine_transaction(&nodes[0], &timeout_tx[0]);
7383 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7384 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7385 expect_payment_failed!(nodes[0], non_dust_hash, false);
7390 fn test_sweep_outbound_htlc_failure_update() {
7391 do_test_sweep_outbound_htlc_failure_update(false, true);
7392 do_test_sweep_outbound_htlc_failure_update(false, false);
7393 do_test_sweep_outbound_htlc_failure_update(true, false);
7397 fn test_user_configurable_csv_delay() {
7398 // We test our channel constructors yield errors when we pass them absurd csv delay
7400 let mut low_our_to_self_config = UserConfig::default();
7401 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7402 let mut high_their_to_self_config = UserConfig::default();
7403 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7404 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7405 let chanmon_cfgs = create_chanmon_cfgs(2);
7406 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7407 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7408 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7410 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7411 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7412 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
7413 &low_our_to_self_config, 0, 42)
7416 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())); },
7417 _ => panic!("Unexpected event"),
7419 } else { assert!(false) }
7421 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7422 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7423 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7424 open_channel.to_self_delay = 200;
7425 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7426 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7427 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7430 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())); },
7431 _ => panic!("Unexpected event"),
7433 } else { assert!(false); }
7435 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7436 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7437 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()));
7438 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7439 accept_channel.to_self_delay = 200;
7440 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
7442 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7444 &ErrorAction::SendErrorMessage { ref msg } => {
7445 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()));
7446 reason_msg = msg.data.clone();
7450 } else { panic!(); }
7451 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7453 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7454 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7455 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7456 open_channel.to_self_delay = 200;
7457 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7458 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
7459 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7462 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())); },
7463 _ => panic!("Unexpected event"),
7465 } else { assert!(false); }
7468 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7469 // When we get a data_loss_protect proving we're behind, we immediately panic as the
7470 // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7471 // panic message informs the user they should force-close without broadcasting, which is tested
7472 // if `reconnect_panicing` is not set.
7478 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7479 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7480 // during signing due to revoked tx
7481 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7482 let keys_manager = &chanmon_cfgs[0].keys_manager;
7485 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7486 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7487 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7489 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7491 // Cache node A state before any channel update
7492 let previous_node_state = nodes[0].node.encode();
7493 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7494 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7496 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7497 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7499 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7500 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7502 // Restore node A from previous state
7503 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7504 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7505 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7506 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7507 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7508 persister = test_utils::TestPersister::new();
7509 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7511 let mut channel_monitors = HashMap::new();
7512 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7513 <(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 {
7514 keys_manager: keys_manager,
7515 fee_estimator: &fee_estimator,
7516 chain_monitor: &monitor,
7518 tx_broadcaster: &tx_broadcaster,
7519 default_config: UserConfig::default(),
7523 nodes[0].node = &node_state_0;
7524 assert_eq!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor),
7525 ChannelMonitorUpdateStatus::Completed);
7526 nodes[0].chain_monitor = &monitor;
7527 nodes[0].chain_source = &chain_source;
7529 check_added_monitors!(nodes[0], 1);
7531 if reconnect_panicing {
7532 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7533 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7535 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7537 // Check we close channel detecting A is fallen-behind
7538 // Check that we sent the warning message when we detected that A has fallen behind,
7539 // and give the possibility for A to recover from the warning.
7540 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7541 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7542 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7545 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7546 // The node B should not broadcast the transaction to force close the channel!
7547 assert!(node_txn.is_empty());
7550 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7551 // Check A panics upon seeing proof it has fallen behind.
7552 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7553 return; // By this point we should have panic'ed!
7556 nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7557 check_added_monitors!(nodes[0], 1);
7558 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7560 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7561 assert_eq!(node_txn.len(), 0);
7564 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7565 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7566 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7568 &ErrorAction::SendErrorMessage { ref msg } => {
7569 assert_eq!(msg.data, "Channel force-closed");
7571 _ => panic!("Unexpected event!"),
7574 panic!("Unexpected event {:?}", msg)
7578 // after the warning message sent by B, we should not able to
7579 // use the channel, or reconnect with success to the channel.
7580 assert!(nodes[0].node.list_usable_channels().is_empty());
7581 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7582 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7583 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7585 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7586 let mut err_msgs_0 = Vec::with_capacity(1);
7587 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7588 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7590 &ErrorAction::SendErrorMessage { ref msg } => {
7591 assert_eq!(msg.data, "Failed to find corresponding channel");
7592 err_msgs_0.push(msg.clone());
7594 _ => panic!("Unexpected event!"),
7597 panic!("Unexpected event!");
7600 assert_eq!(err_msgs_0.len(), 1);
7601 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7602 assert!(nodes[1].node.list_usable_channels().is_empty());
7603 check_added_monitors!(nodes[1], 1);
7604 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7605 check_closed_broadcast!(nodes[1], false);
7610 fn test_data_loss_protect_showing_stale_state_panics() {
7611 do_test_data_loss_protect(true);
7615 fn test_force_close_without_broadcast() {
7616 do_test_data_loss_protect(false);
7620 fn test_check_htlc_underpaying() {
7621 // Send payment through A -> B but A is maliciously
7622 // sending a probe payment (i.e less than expected value0
7623 // to B, B should refuse payment.
7625 let chanmon_cfgs = create_chanmon_cfgs(2);
7626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7628 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7630 // Create some initial channels
7631 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7633 let scorer = test_utils::TestScorer::with_penalty(0);
7634 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7635 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7636 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();
7637 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7638 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7639 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7640 check_added_monitors!(nodes[0], 1);
7642 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7643 assert_eq!(events.len(), 1);
7644 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7645 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7646 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7648 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7649 // and then will wait a second random delay before failing the HTLC back:
7650 expect_pending_htlcs_forwardable!(nodes[1]);
7651 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7653 // Node 3 is expecting payment of 100_000 but received 10_000,
7654 // it should fail htlc like we didn't know the preimage.
7655 nodes[1].node.process_pending_htlc_forwards();
7657 let events = nodes[1].node.get_and_clear_pending_msg_events();
7658 assert_eq!(events.len(), 1);
7659 let (update_fail_htlc, commitment_signed) = match events[0] {
7660 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 } } => {
7661 assert!(update_add_htlcs.is_empty());
7662 assert!(update_fulfill_htlcs.is_empty());
7663 assert_eq!(update_fail_htlcs.len(), 1);
7664 assert!(update_fail_malformed_htlcs.is_empty());
7665 assert!(update_fee.is_none());
7666 (update_fail_htlcs[0].clone(), commitment_signed)
7668 _ => panic!("Unexpected event"),
7670 check_added_monitors!(nodes[1], 1);
7672 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7673 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7675 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7676 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7677 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7678 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7682 fn test_announce_disable_channels() {
7683 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7684 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7686 let chanmon_cfgs = create_chanmon_cfgs(2);
7687 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7688 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7689 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7691 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7692 create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7693 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7696 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7697 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7699 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7700 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7701 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7702 assert_eq!(msg_events.len(), 3);
7703 let mut chans_disabled = HashMap::new();
7704 for e in msg_events {
7706 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7707 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7708 // Check that each channel gets updated exactly once
7709 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7710 panic!("Generated ChannelUpdate for wrong chan!");
7713 _ => panic!("Unexpected event"),
7717 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7718 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7719 assert_eq!(reestablish_1.len(), 3);
7720 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7721 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7722 assert_eq!(reestablish_2.len(), 3);
7724 // Reestablish chan_1
7725 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7726 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7727 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7728 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7729 // Reestablish chan_2
7730 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7731 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7732 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7733 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7734 // Reestablish chan_3
7735 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7736 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7737 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7738 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7740 nodes[0].node.timer_tick_occurred();
7741 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7742 nodes[0].node.timer_tick_occurred();
7743 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7744 assert_eq!(msg_events.len(), 3);
7745 for e in msg_events {
7747 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7748 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7749 match chans_disabled.remove(&msg.contents.short_channel_id) {
7750 // Each update should have a higher timestamp than the previous one, replacing
7752 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7753 None => panic!("Generated ChannelUpdate for wrong chan!"),
7756 _ => panic!("Unexpected event"),
7759 // Check that each channel gets updated exactly once
7760 assert!(chans_disabled.is_empty());
7764 fn test_bump_penalty_txn_on_revoked_commitment() {
7765 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7766 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7768 let chanmon_cfgs = create_chanmon_cfgs(2);
7769 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7770 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7771 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7773 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7775 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7776 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7777 .with_features(channelmanager::provided_invoice_features());
7778 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7779 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7781 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7782 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7783 assert_eq!(revoked_txn[0].output.len(), 4);
7784 assert_eq!(revoked_txn[0].input.len(), 1);
7785 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7786 let revoked_txid = revoked_txn[0].txid();
7788 let mut penalty_sum = 0;
7789 for outp in revoked_txn[0].output.iter() {
7790 if outp.script_pubkey.is_v0_p2wsh() {
7791 penalty_sum += outp.value;
7795 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7796 let header_114 = connect_blocks(&nodes[1], 14);
7798 // Actually revoke tx by claiming a HTLC
7799 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7800 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7801 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7802 check_added_monitors!(nodes[1], 1);
7804 // One or more justice tx should have been broadcast, check it
7808 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7809 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7810 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7811 assert_eq!(node_txn[0].output.len(), 1);
7812 check_spends!(node_txn[0], revoked_txn[0]);
7813 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7814 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7815 penalty_1 = node_txn[0].txid();
7819 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7820 connect_blocks(&nodes[1], 15);
7821 let mut penalty_2 = penalty_1;
7822 let mut feerate_2 = 0;
7824 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7825 assert_eq!(node_txn.len(), 1);
7826 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7827 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7828 assert_eq!(node_txn[0].output.len(), 1);
7829 check_spends!(node_txn[0], revoked_txn[0]);
7830 penalty_2 = node_txn[0].txid();
7831 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7832 assert_ne!(penalty_2, penalty_1);
7833 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7834 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7835 // Verify 25% bump heuristic
7836 assert!(feerate_2 * 100 >= feerate_1 * 125);
7840 assert_ne!(feerate_2, 0);
7842 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7843 connect_blocks(&nodes[1], 1);
7845 let mut feerate_3 = 0;
7847 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7848 assert_eq!(node_txn.len(), 1);
7849 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7850 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7851 assert_eq!(node_txn[0].output.len(), 1);
7852 check_spends!(node_txn[0], revoked_txn[0]);
7853 penalty_3 = node_txn[0].txid();
7854 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7855 assert_ne!(penalty_3, penalty_2);
7856 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7857 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7858 // Verify 25% bump heuristic
7859 assert!(feerate_3 * 100 >= feerate_2 * 125);
7863 assert_ne!(feerate_3, 0);
7865 nodes[1].node.get_and_clear_pending_events();
7866 nodes[1].node.get_and_clear_pending_msg_events();
7870 fn test_bump_penalty_txn_on_revoked_htlcs() {
7871 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7872 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7874 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7875 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7876 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7877 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7878 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7880 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7881 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7882 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7883 let scorer = test_utils::TestScorer::with_penalty(0);
7884 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7885 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7886 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7887 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7888 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7889 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7890 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7891 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7893 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7894 assert_eq!(revoked_local_txn[0].input.len(), 1);
7895 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7897 // Revoke local commitment tx
7898 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7900 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7901 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7902 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7903 check_closed_broadcast!(nodes[1], true);
7904 check_added_monitors!(nodes[1], 1);
7905 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7906 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7908 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7909 assert_eq!(revoked_htlc_txn.len(), 3);
7910 check_spends!(revoked_htlc_txn[1], chan.3);
7912 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7913 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7914 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7916 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7917 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7918 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7919 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7921 // Broadcast set of revoked txn on A
7922 let hash_128 = connect_blocks(&nodes[0], 40);
7923 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7924 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7925 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7926 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7927 let events = nodes[0].node.get_and_clear_pending_events();
7928 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7929 match events.last().unwrap() {
7930 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7931 _ => panic!("Unexpected event"),
7937 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7938 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7939 // Verify claim tx are spending revoked HTLC txn
7941 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7942 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7943 // which are included in the same block (they are broadcasted because we scan the
7944 // transactions linearly and generate claims as we go, they likely should be removed in the
7946 assert_eq!(node_txn[0].input.len(), 1);
7947 check_spends!(node_txn[0], revoked_local_txn[0]);
7948 assert_eq!(node_txn[1].input.len(), 1);
7949 check_spends!(node_txn[1], revoked_local_txn[0]);
7950 assert_eq!(node_txn[2].input.len(), 1);
7951 check_spends!(node_txn[2], revoked_local_txn[0]);
7953 // Each of the three justice transactions claim a separate (single) output of the three
7954 // available, which we check here:
7955 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7956 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7957 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7959 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7960 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7962 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7963 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7964 // a remote commitment tx has already been confirmed).
7965 check_spends!(node_txn[3], chan.3);
7967 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7968 // output, checked above).
7969 assert_eq!(node_txn[4].input.len(), 2);
7970 assert_eq!(node_txn[4].output.len(), 1);
7971 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7973 first = node_txn[4].txid();
7974 // Store both feerates for later comparison
7975 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7976 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7977 penalty_txn = vec![node_txn[2].clone()];
7981 // Connect one more block to see if bumped penalty are issued for HTLC txn
7982 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7983 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7984 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7985 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7987 // Few more blocks to confirm penalty txn
7988 connect_blocks(&nodes[0], 4);
7989 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7990 let header_144 = connect_blocks(&nodes[0], 9);
7992 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7993 assert_eq!(node_txn.len(), 1);
7995 assert_eq!(node_txn[0].input.len(), 2);
7996 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7997 // Verify bumped tx is different and 25% bump heuristic
7998 assert_ne!(first, node_txn[0].txid());
7999 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
8000 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
8001 assert!(feerate_2 * 100 > feerate_1 * 125);
8002 let txn = vec![node_txn[0].clone()];
8006 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8007 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8008 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8009 connect_blocks(&nodes[0], 20);
8011 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8012 // We verify than no new transaction has been broadcast because previously
8013 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8014 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8015 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8016 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8017 // up bumped justice generation.
8018 assert_eq!(node_txn.len(), 0);
8021 check_closed_broadcast!(nodes[0], true);
8022 check_added_monitors!(nodes[0], 1);
8026 fn test_bump_penalty_txn_on_remote_commitment() {
8027 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8028 // we're able to claim outputs on remote commitment transaction before timelocks expiration
8031 // Provide preimage for one
8032 // Check aggregation
8034 let chanmon_cfgs = create_chanmon_cfgs(2);
8035 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8036 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8037 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8039 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8040 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8041 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8043 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8044 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8045 assert_eq!(remote_txn[0].output.len(), 4);
8046 assert_eq!(remote_txn[0].input.len(), 1);
8047 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8049 // Claim a HTLC without revocation (provide B monitor with preimage)
8050 nodes[1].node.claim_funds(payment_preimage);
8051 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8052 mine_transaction(&nodes[1], &remote_txn[0]);
8053 check_added_monitors!(nodes[1], 2);
8054 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8056 // One or more claim tx should have been broadcast, check it
8060 let feerate_timeout;
8061 let feerate_preimage;
8063 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8064 // 5 transactions including:
8065 // local commitment + HTLC-Success
8066 // preimage and timeout sweeps from remote commitment + preimage sweep bump
8067 assert_eq!(node_txn.len(), 5);
8068 assert_eq!(node_txn[0].input.len(), 1);
8069 assert_eq!(node_txn[3].input.len(), 1);
8070 assert_eq!(node_txn[4].input.len(), 1);
8071 check_spends!(node_txn[0], remote_txn[0]);
8072 check_spends!(node_txn[3], remote_txn[0]);
8073 check_spends!(node_txn[4], remote_txn[0]);
8075 check_spends!(node_txn[1], chan.3); // local commitment
8076 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
8078 preimage = node_txn[0].txid();
8079 let index = node_txn[0].input[0].previous_output.vout;
8080 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8081 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8083 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
8084 (node_txn[3].clone(), node_txn[4].clone())
8086 (node_txn[4].clone(), node_txn[3].clone())
8089 preimage_bump = preimage_bump_tx;
8090 check_spends!(preimage_bump, remote_txn[0]);
8091 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
8093 timeout = timeout_tx.txid();
8094 let index = timeout_tx.input[0].previous_output.vout;
8095 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
8096 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
8100 assert_ne!(feerate_timeout, 0);
8101 assert_ne!(feerate_preimage, 0);
8103 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8104 connect_blocks(&nodes[1], 15);
8106 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8107 assert_eq!(node_txn.len(), 1);
8108 assert_eq!(node_txn[0].input.len(), 1);
8109 assert_eq!(preimage_bump.input.len(), 1);
8110 check_spends!(node_txn[0], remote_txn[0]);
8111 check_spends!(preimage_bump, remote_txn[0]);
8113 let index = preimage_bump.input[0].previous_output.vout;
8114 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8115 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8116 assert!(new_feerate * 100 > feerate_timeout * 125);
8117 assert_ne!(timeout, preimage_bump.txid());
8119 let index = node_txn[0].input[0].previous_output.vout;
8120 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8121 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8122 assert!(new_feerate * 100 > feerate_preimage * 125);
8123 assert_ne!(preimage, node_txn[0].txid());
8128 nodes[1].node.get_and_clear_pending_events();
8129 nodes[1].node.get_and_clear_pending_msg_events();
8133 fn test_counterparty_raa_skip_no_crash() {
8134 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8135 // commitment transaction, we would have happily carried on and provided them the next
8136 // commitment transaction based on one RAA forward. This would probably eventually have led to
8137 // channel closure, but it would not have resulted in funds loss. Still, our
8138 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8139 // check simply that the channel is closed in response to such an RAA, but don't check whether
8140 // we decide to punish our counterparty for revoking their funds (as we don't currently
8142 let chanmon_cfgs = create_chanmon_cfgs(2);
8143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8145 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8146 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
8148 let per_commitment_secret;
8149 let next_per_commitment_point;
8151 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8152 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8154 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8156 // Make signer believe we got a counterparty signature, so that it allows the revocation
8157 keys.get_enforcement_state().last_holder_commitment -= 1;
8158 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8160 // Must revoke without gaps
8161 keys.get_enforcement_state().last_holder_commitment -= 1;
8162 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8164 keys.get_enforcement_state().last_holder_commitment -= 1;
8165 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8166 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8169 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8170 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8171 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8172 check_added_monitors!(nodes[1], 1);
8173 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8177 fn test_bump_txn_sanitize_tracking_maps() {
8178 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8179 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8181 let chanmon_cfgs = create_chanmon_cfgs(2);
8182 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8183 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8184 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8186 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8187 // Lock HTLC in both directions
8188 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8189 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8191 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8192 assert_eq!(revoked_local_txn[0].input.len(), 1);
8193 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8195 // Revoke local commitment tx
8196 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8198 // Broadcast set of revoked txn on A
8199 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8200 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8201 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8203 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8204 check_closed_broadcast!(nodes[0], true);
8205 check_added_monitors!(nodes[0], 1);
8206 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8208 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8209 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8210 check_spends!(node_txn[0], revoked_local_txn[0]);
8211 check_spends!(node_txn[1], revoked_local_txn[0]);
8212 check_spends!(node_txn[2], revoked_local_txn[0]);
8213 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8217 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8218 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8219 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8221 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8222 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8223 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8228 fn test_pending_claimed_htlc_no_balance_underflow() {
8229 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8230 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8231 let chanmon_cfgs = create_chanmon_cfgs(2);
8232 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8233 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8234 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8235 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8237 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8238 nodes[1].node.claim_funds(payment_preimage);
8239 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8240 check_added_monitors!(nodes[1], 1);
8241 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8243 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8244 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8245 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8246 check_added_monitors!(nodes[0], 1);
8247 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8249 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8250 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8251 // can get our balance.
8253 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8254 // the public key of the only hop. This works around ChannelDetails not showing the
8255 // almost-claimed HTLC as available balance.
8256 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8257 route.payment_params = None; // This is all wrong, but unnecessary
8258 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8259 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8260 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8262 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8266 fn test_channel_conf_timeout() {
8267 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8268 // confirm within 2016 blocks, as recommended by BOLT 2.
8269 let chanmon_cfgs = create_chanmon_cfgs(2);
8270 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8271 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8272 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8274 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());
8276 // The outbound node should wait forever for confirmation:
8277 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8278 // copied here instead of directly referencing the constant.
8279 connect_blocks(&nodes[0], 2016);
8280 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8282 // The inbound node should fail the channel after exactly 2016 blocks
8283 connect_blocks(&nodes[1], 2015);
8284 check_added_monitors!(nodes[1], 0);
8285 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8287 connect_blocks(&nodes[1], 1);
8288 check_added_monitors!(nodes[1], 1);
8289 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8290 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8291 assert_eq!(close_ev.len(), 1);
8293 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8294 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8295 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8297 _ => panic!("Unexpected event"),
8302 fn test_override_channel_config() {
8303 let chanmon_cfgs = create_chanmon_cfgs(2);
8304 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8305 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8306 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8308 // Node0 initiates a channel to node1 using the override config.
8309 let mut override_config = UserConfig::default();
8310 override_config.channel_handshake_config.our_to_self_delay = 200;
8312 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8314 // Assert the channel created by node0 is using the override config.
8315 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8316 assert_eq!(res.channel_flags, 0);
8317 assert_eq!(res.to_self_delay, 200);
8321 fn test_override_0msat_htlc_minimum() {
8322 let mut zero_config = UserConfig::default();
8323 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8324 let chanmon_cfgs = create_chanmon_cfgs(2);
8325 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8326 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8327 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8329 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8330 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8331 assert_eq!(res.htlc_minimum_msat, 1);
8333 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8334 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8335 assert_eq!(res.htlc_minimum_msat, 1);
8339 fn test_channel_update_has_correct_htlc_maximum_msat() {
8340 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8341 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8342 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8343 // 90% of the `channel_value`.
8344 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8346 let mut config_30_percent = UserConfig::default();
8347 config_30_percent.channel_handshake_config.announced_channel = true;
8348 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8349 let mut config_50_percent = UserConfig::default();
8350 config_50_percent.channel_handshake_config.announced_channel = true;
8351 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8352 let mut config_95_percent = UserConfig::default();
8353 config_95_percent.channel_handshake_config.announced_channel = true;
8354 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8355 let mut config_100_percent = UserConfig::default();
8356 config_100_percent.channel_handshake_config.announced_channel = true;
8357 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8359 let chanmon_cfgs = create_chanmon_cfgs(4);
8360 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8361 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)]);
8362 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8364 let channel_value_satoshis = 100000;
8365 let channel_value_msat = channel_value_satoshis * 1000;
8366 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8367 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8368 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8370 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());
8371 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());
8373 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8374 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8375 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8376 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8377 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8378 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8380 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8381 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8383 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8384 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8385 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8387 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8391 fn test_manually_accept_inbound_channel_request() {
8392 let mut manually_accept_conf = UserConfig::default();
8393 manually_accept_conf.manually_accept_inbound_channels = true;
8394 let chanmon_cfgs = create_chanmon_cfgs(2);
8395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8399 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8400 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8402 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8404 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8405 // accepting the inbound channel request.
8406 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8408 let events = nodes[1].node.get_and_clear_pending_events();
8410 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8411 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8413 _ => panic!("Unexpected event"),
8416 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8417 assert_eq!(accept_msg_ev.len(), 1);
8419 match accept_msg_ev[0] {
8420 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8421 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8423 _ => panic!("Unexpected event"),
8426 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8428 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8429 assert_eq!(close_msg_ev.len(), 1);
8431 let events = nodes[1].node.get_and_clear_pending_events();
8433 Event::ChannelClosed { user_channel_id, .. } => {
8434 assert_eq!(user_channel_id, 23);
8436 _ => panic!("Unexpected event"),
8441 fn test_manually_reject_inbound_channel_request() {
8442 let mut manually_accept_conf = UserConfig::default();
8443 manually_accept_conf.manually_accept_inbound_channels = true;
8444 let chanmon_cfgs = create_chanmon_cfgs(2);
8445 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8446 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8447 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8449 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8450 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8452 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8454 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8455 // rejecting the inbound channel request.
8456 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8458 let events = nodes[1].node.get_and_clear_pending_events();
8460 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8461 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8463 _ => panic!("Unexpected event"),
8466 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8467 assert_eq!(close_msg_ev.len(), 1);
8469 match close_msg_ev[0] {
8470 MessageSendEvent::HandleError { ref node_id, .. } => {
8471 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8473 _ => panic!("Unexpected event"),
8475 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8479 fn test_reject_funding_before_inbound_channel_accepted() {
8480 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8481 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8482 // the node operator before the counterparty sends a `FundingCreated` message. If a
8483 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8484 // and the channel should be closed.
8485 let mut manually_accept_conf = UserConfig::default();
8486 manually_accept_conf.manually_accept_inbound_channels = true;
8487 let chanmon_cfgs = create_chanmon_cfgs(2);
8488 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8489 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8490 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8492 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8493 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8494 let temp_channel_id = res.temporary_channel_id;
8496 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8498 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8499 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8501 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8502 nodes[1].node.get_and_clear_pending_events();
8504 // Get the `AcceptChannel` message of `nodes[1]` without calling
8505 // `ChannelManager::accept_inbound_channel`, which generates a
8506 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8507 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8508 // succeed when `nodes[0]` is passed to it.
8509 let accept_chan_msg = {
8511 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8512 channel.get_accept_channel_message()
8514 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8516 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8518 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8519 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8521 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8522 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8524 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8525 assert_eq!(close_msg_ev.len(), 1);
8527 let expected_err = "FundingCreated message received before the channel was accepted";
8528 match close_msg_ev[0] {
8529 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8530 assert_eq!(msg.channel_id, temp_channel_id);
8531 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8532 assert_eq!(msg.data, expected_err);
8534 _ => panic!("Unexpected event"),
8537 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8541 fn test_can_not_accept_inbound_channel_twice() {
8542 let mut manually_accept_conf = UserConfig::default();
8543 manually_accept_conf.manually_accept_inbound_channels = true;
8544 let chanmon_cfgs = create_chanmon_cfgs(2);
8545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8547 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8549 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8550 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8552 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
8554 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8555 // accepting the inbound channel request.
8556 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8558 let events = nodes[1].node.get_and_clear_pending_events();
8560 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8561 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8562 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8564 Err(APIError::APIMisuseError { err }) => {
8565 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8567 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8568 Err(_) => panic!("Unexpected Error"),
8571 _ => panic!("Unexpected event"),
8574 // Ensure that the channel wasn't closed after attempting to accept it twice.
8575 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8576 assert_eq!(accept_msg_ev.len(), 1);
8578 match accept_msg_ev[0] {
8579 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8580 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8582 _ => panic!("Unexpected event"),
8587 fn test_can_not_accept_unknown_inbound_channel() {
8588 let chanmon_cfg = create_chanmon_cfgs(2);
8589 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8590 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8591 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8593 let unknown_channel_id = [0; 32];
8594 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8596 Err(APIError::ChannelUnavailable { err }) => {
8597 assert_eq!(err, "Can't accept a channel that doesn't exist");
8599 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8600 Err(_) => panic!("Unexpected Error"),
8605 fn test_simple_mpp() {
8606 // Simple test of sending a multi-path payment.
8607 let chanmon_cfgs = create_chanmon_cfgs(4);
8608 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8609 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8610 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8612 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;
8613 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;
8614 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;
8615 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;
8617 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8618 let path = route.paths[0].clone();
8619 route.paths.push(path);
8620 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8621 route.paths[0][0].short_channel_id = chan_1_id;
8622 route.paths[0][1].short_channel_id = chan_3_id;
8623 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8624 route.paths[1][0].short_channel_id = chan_2_id;
8625 route.paths[1][1].short_channel_id = chan_4_id;
8626 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8627 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8631 fn test_preimage_storage() {
8632 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8633 let chanmon_cfgs = create_chanmon_cfgs(2);
8634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8636 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8638 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8641 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8642 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8643 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8644 check_added_monitors!(nodes[0], 1);
8645 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8646 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8647 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8648 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8650 // Note that after leaving the above scope we have no knowledge of any arguments or return
8651 // values from previous calls.
8652 expect_pending_htlcs_forwardable!(nodes[1]);
8653 let events = nodes[1].node.get_and_clear_pending_events();
8654 assert_eq!(events.len(), 1);
8656 Event::PaymentReceived { ref purpose, .. } => {
8658 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8659 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8661 _ => panic!("expected PaymentPurpose::InvoicePayment")
8664 _ => panic!("Unexpected event"),
8669 #[allow(deprecated)]
8670 fn test_secret_timeout() {
8671 // Simple test of payment secret storage time outs. After
8672 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8673 let chanmon_cfgs = create_chanmon_cfgs(2);
8674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8676 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8678 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8680 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8682 // We should fail to register the same payment hash twice, at least until we've connected a
8683 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8684 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8685 assert_eq!(err, "Duplicate payment hash");
8686 } else { panic!(); }
8688 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8690 header: BlockHeader {
8692 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8693 merkle_root: TxMerkleNode::all_zeros(),
8694 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8698 connect_block(&nodes[1], &block);
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 // If we then connect the second block, we should be able to register the same payment hash
8704 // again (this time getting a new payment secret).
8705 block.header.prev_blockhash = block.header.block_hash();
8706 block.header.time += 1;
8707 connect_block(&nodes[1], &block);
8708 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8709 assert_ne!(payment_secret_1, our_payment_secret);
8712 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8713 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8714 check_added_monitors!(nodes[0], 1);
8715 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8716 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8717 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8718 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8720 // Note that after leaving the above scope we have no knowledge of any arguments or return
8721 // values from previous calls.
8722 expect_pending_htlcs_forwardable!(nodes[1]);
8723 let events = nodes[1].node.get_and_clear_pending_events();
8724 assert_eq!(events.len(), 1);
8726 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8727 assert!(payment_preimage.is_none());
8728 assert_eq!(payment_secret, our_payment_secret);
8729 // We don't actually have the payment preimage with which to claim this payment!
8731 _ => panic!("Unexpected event"),
8736 fn test_bad_secret_hash() {
8737 // Simple test of unregistered payment hash/invalid payment secret handling
8738 let chanmon_cfgs = create_chanmon_cfgs(2);
8739 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8740 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8741 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8743 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8745 let random_payment_hash = PaymentHash([42; 32]);
8746 let random_payment_secret = PaymentSecret([43; 32]);
8747 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8748 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8750 // All the below cases should end up being handled exactly identically, so we macro the
8751 // resulting events.
8752 macro_rules! handle_unknown_invalid_payment_data {
8753 ($payment_hash: expr) => {
8754 check_added_monitors!(nodes[0], 1);
8755 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8756 let payment_event = SendEvent::from_event(events.pop().unwrap());
8757 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8758 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8760 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8761 // again to process the pending backwards-failure of the HTLC
8762 expect_pending_htlcs_forwardable!(nodes[1]);
8763 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8764 check_added_monitors!(nodes[1], 1);
8766 // We should fail the payment back
8767 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8768 match events.pop().unwrap() {
8769 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8770 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8771 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8773 _ => panic!("Unexpected event"),
8778 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8779 // Error data is the HTLC value (100,000) and current block height
8780 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8782 // Send a payment with the right payment hash but the wrong payment secret
8783 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8784 handle_unknown_invalid_payment_data!(our_payment_hash);
8785 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8787 // Send a payment with a random payment hash, but the right payment secret
8788 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8789 handle_unknown_invalid_payment_data!(random_payment_hash);
8790 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8792 // Send a payment with a random payment hash and random payment secret
8793 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8794 handle_unknown_invalid_payment_data!(random_payment_hash);
8795 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8799 fn test_update_err_monitor_lockdown() {
8800 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8801 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8802 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8805 // This scenario may happen in a watchtower setup, where watchtower process a block height
8806 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8807 // commitment at same time.
8809 let chanmon_cfgs = create_chanmon_cfgs(2);
8810 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8811 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8812 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8814 // Create some initial channel
8815 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8816 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8818 // Rebalance the network to generate htlc in the two directions
8819 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8821 // Route a HTLC from node 0 to node 1 (but don't settle)
8822 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8824 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8825 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8826 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8827 let persister = test_utils::TestPersister::new();
8829 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8830 let mut w = test_utils::TestVecWriter(Vec::new());
8831 monitor.write(&mut w).unwrap();
8832 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8833 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8834 assert!(new_monitor == *monitor);
8835 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);
8836 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8839 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8840 let block = Block { header, txdata: vec![] };
8841 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8842 // transaction lock time requirements here.
8843 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8844 watchtower.chain_monitor.block_connected(&block, 200);
8846 // Try to update ChannelMonitor
8847 nodes[1].node.claim_funds(preimage);
8848 check_added_monitors!(nodes[1], 1);
8849 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8851 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8852 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8853 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8854 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8855 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8856 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8857 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8858 } else { assert!(false); }
8859 } else { assert!(false); };
8860 // Our local monitor is in-sync and hasn't processed yet timeout
8861 check_added_monitors!(nodes[0], 1);
8862 let events = nodes[0].node.get_and_clear_pending_events();
8863 assert_eq!(events.len(), 1);
8867 fn test_concurrent_monitor_claim() {
8868 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8869 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8870 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8871 // state N+1 confirms. Alice claims output from state N+1.
8873 let chanmon_cfgs = create_chanmon_cfgs(2);
8874 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8875 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8876 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8878 // Create some initial channel
8879 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8880 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8882 // Rebalance the network to generate htlc in the two directions
8883 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8885 // Route a HTLC from node 0 to node 1 (but don't settle)
8886 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8888 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8889 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8890 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8891 let persister = test_utils::TestPersister::new();
8892 let watchtower_alice = {
8893 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8894 let mut w = test_utils::TestVecWriter(Vec::new());
8895 monitor.write(&mut w).unwrap();
8896 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8897 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8898 assert!(new_monitor == *monitor);
8899 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);
8900 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8903 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8904 let block = Block { header, txdata: vec![] };
8905 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8906 // transaction lock time requirements here.
8907 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));
8908 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8910 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8912 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8913 assert_eq!(txn.len(), 2);
8917 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8918 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8919 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8920 let persister = test_utils::TestPersister::new();
8921 let watchtower_bob = {
8922 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8923 let mut w = test_utils::TestVecWriter(Vec::new());
8924 monitor.write(&mut w).unwrap();
8925 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8926 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8927 assert!(new_monitor == *monitor);
8928 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);
8929 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8932 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8933 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8935 // Route another payment to generate another update with still previous HTLC pending
8936 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8938 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8940 check_added_monitors!(nodes[1], 1);
8942 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8943 assert_eq!(updates.update_add_htlcs.len(), 1);
8944 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8945 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8946 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8947 // Watchtower Alice should already have seen the block and reject the update
8948 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8949 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8950 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8951 } else { assert!(false); }
8952 } else { assert!(false); };
8953 // Our local monitor is in-sync and hasn't processed yet timeout
8954 check_added_monitors!(nodes[0], 1);
8956 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8957 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8958 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8960 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8963 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8964 assert_eq!(txn.len(), 2);
8965 bob_state_y = txn[0].clone();
8969 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8970 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8971 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);
8973 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8974 assert_eq!(htlc_txn.len(), 1);
8975 check_spends!(htlc_txn[0], bob_state_y);
8980 fn test_pre_lockin_no_chan_closed_update() {
8981 // Test that if a peer closes a channel in response to a funding_created message we don't
8982 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8985 // Doing so would imply a channel monitor update before the initial channel monitor
8986 // registration, violating our API guarantees.
8988 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8989 // then opening a second channel with the same funding output as the first (which is not
8990 // rejected because the first channel does not exist in the ChannelManager) and closing it
8991 // before receiving funding_signed.
8992 let chanmon_cfgs = create_chanmon_cfgs(2);
8993 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8994 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8995 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8997 // Create an initial channel
8998 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8999 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9000 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9001 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9002 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
9004 // Move the first channel through the funding flow...
9005 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9007 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9008 check_added_monitors!(nodes[0], 0);
9010 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9011 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
9012 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
9013 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
9014 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
9018 fn test_htlc_no_detection() {
9019 // This test is a mutation to underscore the detection logic bug we had
9020 // before #653. HTLC value routed is above the remaining balance, thus
9021 // inverting HTLC and `to_remote` output. HTLC will come second and
9022 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9023 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9024 // outputs order detection for correct spending children filtring.
9026 let chanmon_cfgs = create_chanmon_cfgs(2);
9027 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9028 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9029 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9031 // Create some initial channels
9032 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9034 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9035 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9036 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9037 assert_eq!(local_txn[0].input.len(), 1);
9038 assert_eq!(local_txn[0].output.len(), 3);
9039 check_spends!(local_txn[0], chan_1.3);
9041 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9042 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9043 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9044 // We deliberately connect the local tx twice as this should provoke a failure calling
9045 // this test before #653 fix.
9046 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);
9047 check_closed_broadcast!(nodes[0], true);
9048 check_added_monitors!(nodes[0], 1);
9049 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9050 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9052 let htlc_timeout = {
9053 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9054 assert_eq!(node_txn[1].input.len(), 1);
9055 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9056 check_spends!(node_txn[1], local_txn[0]);
9060 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9061 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9062 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9063 expect_payment_failed!(nodes[0], our_payment_hash, false);
9066 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9067 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9068 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9069 // Carol, Alice would be the upstream node, and Carol the downstream.)
9071 // Steps of the test:
9072 // 1) Alice sends a HTLC to Carol through Bob.
9073 // 2) Carol doesn't settle the HTLC.
9074 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9075 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9076 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9077 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9078 // 5) Carol release the preimage to Bob off-chain.
9079 // 6) Bob claims the offered output on the broadcasted commitment.
9080 let chanmon_cfgs = create_chanmon_cfgs(3);
9081 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9082 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9083 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9085 // Create some initial channels
9086 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9087 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9089 // Steps (1) and (2):
9090 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9091 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9093 // Check that Alice's commitment transaction now contains an output for this HTLC.
9094 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9095 check_spends!(alice_txn[0], chan_ab.3);
9096 assert_eq!(alice_txn[0].output.len(), 2);
9097 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9098 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9099 assert_eq!(alice_txn.len(), 2);
9101 // Steps (3) and (4):
9102 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9103 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9104 let mut force_closing_node = 0; // Alice force-closes
9105 let mut counterparty_node = 1; // Bob if Alice force-closes
9108 if !broadcast_alice {
9109 force_closing_node = 1;
9110 counterparty_node = 0;
9112 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9113 check_closed_broadcast!(nodes[force_closing_node], true);
9114 check_added_monitors!(nodes[force_closing_node], 1);
9115 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9116 if go_onchain_before_fulfill {
9117 let txn_to_broadcast = match broadcast_alice {
9118 true => alice_txn.clone(),
9119 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9121 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9122 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9123 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9124 if broadcast_alice {
9125 check_closed_broadcast!(nodes[1], true);
9126 check_added_monitors!(nodes[1], 1);
9127 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9129 assert_eq!(bob_txn.len(), 1);
9130 check_spends!(bob_txn[0], chan_ab.3);
9134 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9135 // process of removing the HTLC from their commitment transactions.
9136 nodes[2].node.claim_funds(payment_preimage);
9137 check_added_monitors!(nodes[2], 1);
9138 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9140 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9141 assert!(carol_updates.update_add_htlcs.is_empty());
9142 assert!(carol_updates.update_fail_htlcs.is_empty());
9143 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9144 assert!(carol_updates.update_fee.is_none());
9145 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9147 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9148 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9149 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9150 if !go_onchain_before_fulfill && broadcast_alice {
9151 let events = nodes[1].node.get_and_clear_pending_msg_events();
9152 assert_eq!(events.len(), 1);
9154 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9155 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9157 _ => panic!("Unexpected event"),
9160 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9161 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9162 // Carol<->Bob's updated commitment transaction info.
9163 check_added_monitors!(nodes[1], 2);
9165 let events = nodes[1].node.get_and_clear_pending_msg_events();
9166 assert_eq!(events.len(), 2);
9167 let bob_revocation = match events[0] {
9168 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9169 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9172 _ => panic!("Unexpected event"),
9174 let bob_updates = match events[1] {
9175 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9176 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9179 _ => panic!("Unexpected event"),
9182 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9183 check_added_monitors!(nodes[2], 1);
9184 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9185 check_added_monitors!(nodes[2], 1);
9187 let events = nodes[2].node.get_and_clear_pending_msg_events();
9188 assert_eq!(events.len(), 1);
9189 let carol_revocation = match events[0] {
9190 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9191 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9194 _ => panic!("Unexpected event"),
9196 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9197 check_added_monitors!(nodes[1], 1);
9199 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9200 // here's where we put said channel's commitment tx on-chain.
9201 let mut txn_to_broadcast = alice_txn.clone();
9202 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9203 if !go_onchain_before_fulfill {
9204 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9205 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9206 // If Bob was the one to force-close, he will have already passed these checks earlier.
9207 if broadcast_alice {
9208 check_closed_broadcast!(nodes[1], true);
9209 check_added_monitors!(nodes[1], 1);
9210 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9212 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9213 if broadcast_alice {
9214 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9215 // new block being connected. The ChannelManager being notified triggers a monitor update,
9216 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9217 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9219 assert_eq!(bob_txn.len(), 3);
9220 check_spends!(bob_txn[1], chan_ab.3);
9222 assert_eq!(bob_txn.len(), 2);
9223 check_spends!(bob_txn[0], chan_ab.3);
9228 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9229 // broadcasted commitment transaction.
9231 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9232 if go_onchain_before_fulfill {
9233 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9234 assert_eq!(bob_txn.len(), 2);
9236 let script_weight = match broadcast_alice {
9237 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9238 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9240 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9241 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9242 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9243 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9244 if broadcast_alice && !go_onchain_before_fulfill {
9245 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9246 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9248 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9249 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9255 fn test_onchain_htlc_settlement_after_close() {
9256 do_test_onchain_htlc_settlement_after_close(true, true);
9257 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9258 do_test_onchain_htlc_settlement_after_close(true, false);
9259 do_test_onchain_htlc_settlement_after_close(false, false);
9263 fn test_duplicate_chan_id() {
9264 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9265 // already open we reject it and keep the old channel.
9267 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9268 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9269 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9270 // updating logic for the existing channel.
9271 let chanmon_cfgs = create_chanmon_cfgs(2);
9272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9274 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9276 // Create an initial channel
9277 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9278 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9279 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9280 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()));
9282 // Try to create a second channel with the same temporary_channel_id as the first and check
9283 // that it is rejected.
9284 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9286 let events = nodes[1].node.get_and_clear_pending_msg_events();
9287 assert_eq!(events.len(), 1);
9289 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9290 // Technically, at this point, nodes[1] would be justified in thinking both the
9291 // first (valid) and second (invalid) channels are closed, given they both have
9292 // the same non-temporary channel_id. However, currently we do not, so we just
9293 // move forward with it.
9294 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9295 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9297 _ => panic!("Unexpected event"),
9301 // Move the first channel through the funding flow...
9302 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9304 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9305 check_added_monitors!(nodes[0], 0);
9307 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9308 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9310 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9311 assert_eq!(added_monitors.len(), 1);
9312 assert_eq!(added_monitors[0].0, funding_output);
9313 added_monitors.clear();
9315 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9317 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9318 let channel_id = funding_outpoint.to_channel_id();
9320 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9323 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9324 // Technically this is allowed by the spec, but we don't support it and there's little reason
9325 // to. Still, it shouldn't cause any other issues.
9326 open_chan_msg.temporary_channel_id = channel_id;
9327 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
9329 let events = nodes[1].node.get_and_clear_pending_msg_events();
9330 assert_eq!(events.len(), 1);
9332 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9333 // Technically, at this point, nodes[1] would be justified in thinking both
9334 // channels are closed, but currently we do not, so we just move forward with it.
9335 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9336 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9338 _ => panic!("Unexpected event"),
9342 // Now try to create a second channel which has a duplicate funding output.
9343 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9344 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9345 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
9346 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()));
9347 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9349 let funding_created = {
9350 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9351 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9352 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9353 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9354 // channelmanager in a possibly nonsense state instead).
9355 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9356 let logger = test_utils::TestLogger::new();
9357 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9359 check_added_monitors!(nodes[0], 0);
9360 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9361 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9362 // still needs to be cleared here.
9363 check_added_monitors!(nodes[1], 1);
9365 // ...still, nodes[1] will reject the duplicate channel.
9367 let events = nodes[1].node.get_and_clear_pending_msg_events();
9368 assert_eq!(events.len(), 1);
9370 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9371 // Technically, at this point, nodes[1] would be justified in thinking both
9372 // channels are closed, but currently we do not, so we just move forward with it.
9373 assert_eq!(msg.channel_id, channel_id);
9374 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9376 _ => panic!("Unexpected event"),
9380 // finally, finish creating the original channel and send a payment over it to make sure
9381 // everything is functional.
9382 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9384 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9385 assert_eq!(added_monitors.len(), 1);
9386 assert_eq!(added_monitors[0].0, funding_output);
9387 added_monitors.clear();
9390 let events_4 = nodes[0].node.get_and_clear_pending_events();
9391 assert_eq!(events_4.len(), 0);
9392 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9393 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9395 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9396 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9397 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9398 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9402 fn test_error_chans_closed() {
9403 // Test that we properly handle error messages, closing appropriate channels.
9405 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9406 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9407 // we can test various edge cases around it to ensure we don't regress.
9408 let chanmon_cfgs = create_chanmon_cfgs(3);
9409 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9410 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9411 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9413 // Create some initial channels
9414 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9415 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9416 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9418 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9419 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9420 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9422 // Closing a channel from a different peer has no effect
9423 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9424 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9426 // Closing one channel doesn't impact others
9427 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9428 check_added_monitors!(nodes[0], 1);
9429 check_closed_broadcast!(nodes[0], false);
9430 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9431 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9432 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9433 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);
9434 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);
9436 // A null channel ID should close all channels
9437 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9438 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9439 check_added_monitors!(nodes[0], 2);
9440 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9441 let events = nodes[0].node.get_and_clear_pending_msg_events();
9442 assert_eq!(events.len(), 2);
9444 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9445 assert_eq!(msg.contents.flags & 2, 2);
9447 _ => panic!("Unexpected event"),
9450 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9451 assert_eq!(msg.contents.flags & 2, 2);
9453 _ => panic!("Unexpected event"),
9455 // Note that at this point users of a standard PeerHandler will end up calling
9456 // peer_disconnected with no_connection_possible set to false, duplicating the
9457 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9458 // users with their own peer handling logic. We duplicate the call here, however.
9459 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9460 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9462 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9463 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9464 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9468 fn test_invalid_funding_tx() {
9469 // Test that we properly handle invalid funding transactions sent to us from a peer.
9471 // Previously, all other major lightning implementations had failed to properly sanitize
9472 // funding transactions from their counterparties, leading to a multi-implementation critical
9473 // security vulnerability (though we always sanitized properly, we've previously had
9474 // un-released crashes in the sanitization process).
9476 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9477 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9478 // gave up on it. We test this here by generating such a transaction.
9479 let chanmon_cfgs = create_chanmon_cfgs(2);
9480 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9481 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9482 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9484 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9485 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()));
9486 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()));
9488 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9490 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9491 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9492 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9494 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9495 let wit_program_script: Script = wit_program.into();
9496 for output in tx.output.iter_mut() {
9497 // Make the confirmed funding transaction have a bogus script_pubkey
9498 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9501 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9502 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()));
9503 check_added_monitors!(nodes[1], 1);
9505 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()));
9506 check_added_monitors!(nodes[0], 1);
9508 let events_1 = nodes[0].node.get_and_clear_pending_events();
9509 assert_eq!(events_1.len(), 0);
9511 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9512 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9513 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9515 let expected_err = "funding tx had wrong script/value or output index";
9516 confirm_transaction_at(&nodes[1], &tx, 1);
9517 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9518 check_added_monitors!(nodes[1], 1);
9519 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9520 assert_eq!(events_2.len(), 1);
9521 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9522 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9523 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9524 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9525 } else { panic!(); }
9526 } else { panic!(); }
9527 assert_eq!(nodes[1].node.list_channels().len(), 0);
9529 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9530 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9531 // as its not 32 bytes long.
9532 let mut spend_tx = Transaction {
9533 version: 2i32, lock_time: PackedLockTime::ZERO,
9534 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9535 previous_output: BitcoinOutPoint {
9539 script_sig: Script::new(),
9540 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9541 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9543 output: vec![TxOut {
9545 script_pubkey: Script::new(),
9548 check_spends!(spend_tx, tx);
9549 mine_transaction(&nodes[1], &spend_tx);
9552 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9553 // In the first version of the chain::Confirm interface, after a refactor was made to not
9554 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9555 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9556 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9557 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9558 // spending transaction until height N+1 (or greater). This was due to the way
9559 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9560 // spending transaction at the height the input transaction was confirmed at, not whether we
9561 // should broadcast a spending transaction at the current height.
9562 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9563 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9564 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9565 // until we learned about an additional block.
9567 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9568 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9569 let chanmon_cfgs = create_chanmon_cfgs(3);
9570 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9571 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9572 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9573 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9575 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9576 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9577 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9578 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9579 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9581 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9582 check_closed_broadcast!(nodes[1], true);
9583 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9584 check_added_monitors!(nodes[1], 1);
9585 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9586 assert_eq!(node_txn.len(), 1);
9588 let conf_height = nodes[1].best_block_info().1;
9589 if !test_height_before_timelock {
9590 connect_blocks(&nodes[1], 24 * 6);
9592 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9593 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9594 if test_height_before_timelock {
9595 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9596 // generate any events or broadcast any transactions
9597 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9598 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9600 // We should broadcast an HTLC transaction spending our funding transaction first
9601 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9602 assert_eq!(spending_txn.len(), 2);
9603 assert_eq!(spending_txn[0], node_txn[0]);
9604 check_spends!(spending_txn[1], node_txn[0]);
9605 // We should also generate a SpendableOutputs event with the to_self output (as its
9607 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9608 assert_eq!(descriptor_spend_txn.len(), 1);
9610 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9611 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9612 // additional block built on top of the current chain.
9613 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9614 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9615 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 }]);
9616 check_added_monitors!(nodes[1], 1);
9618 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9619 assert!(updates.update_add_htlcs.is_empty());
9620 assert!(updates.update_fulfill_htlcs.is_empty());
9621 assert_eq!(updates.update_fail_htlcs.len(), 1);
9622 assert!(updates.update_fail_malformed_htlcs.is_empty());
9623 assert!(updates.update_fee.is_none());
9624 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9625 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9626 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9631 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9632 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9633 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9637 fn test_forwardable_regen() {
9638 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9639 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9641 // We test it for both payment receipt and payment forwarding.
9643 let chanmon_cfgs = create_chanmon_cfgs(3);
9644 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9645 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9646 let persister: test_utils::TestPersister;
9647 let new_chain_monitor: test_utils::TestChainMonitor;
9648 let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9649 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9650 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9651 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
9653 // First send a payment to nodes[1]
9654 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9655 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9656 check_added_monitors!(nodes[0], 1);
9658 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9659 assert_eq!(events.len(), 1);
9660 let payment_event = SendEvent::from_event(events.pop().unwrap());
9661 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9662 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9664 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9666 // Next send a payment which is forwarded by nodes[1]
9667 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9668 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9669 check_added_monitors!(nodes[0], 1);
9671 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9672 assert_eq!(events.len(), 1);
9673 let payment_event = SendEvent::from_event(events.pop().unwrap());
9674 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9675 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9677 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9679 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9681 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9682 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9683 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9685 let nodes_1_serialized = nodes[1].node.encode();
9686 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9687 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9688 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9689 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9691 persister = test_utils::TestPersister::new();
9692 let keys_manager = &chanmon_cfgs[1].keys_manager;
9693 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);
9694 nodes[1].chain_monitor = &new_chain_monitor;
9696 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9697 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9698 &mut chan_0_monitor_read, keys_manager).unwrap();
9699 assert!(chan_0_monitor_read.is_empty());
9700 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9701 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9702 &mut chan_1_monitor_read, keys_manager).unwrap();
9703 assert!(chan_1_monitor_read.is_empty());
9705 let mut nodes_1_read = &nodes_1_serialized[..];
9706 let (_, nodes_1_deserialized_tmp) = {
9707 let mut channel_monitors = HashMap::new();
9708 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9709 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9710 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9711 default_config: UserConfig::default(),
9713 fee_estimator: node_cfgs[1].fee_estimator,
9714 chain_monitor: nodes[1].chain_monitor,
9715 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9716 logger: nodes[1].logger,
9720 nodes_1_deserialized = nodes_1_deserialized_tmp;
9721 assert!(nodes_1_read.is_empty());
9723 assert_eq!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
9724 ChannelMonitorUpdateStatus::Completed);
9725 assert_eq!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor),
9726 ChannelMonitorUpdateStatus::Completed);
9727 nodes[1].node = &nodes_1_deserialized;
9728 check_added_monitors!(nodes[1], 2);
9730 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9731 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9732 // the commitment state.
9733 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9735 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9737 expect_pending_htlcs_forwardable!(nodes[1]);
9738 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9739 check_added_monitors!(nodes[1], 1);
9741 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9742 assert_eq!(events.len(), 1);
9743 let payment_event = SendEvent::from_event(events.pop().unwrap());
9744 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9745 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9746 expect_pending_htlcs_forwardable!(nodes[2]);
9747 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9749 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9750 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9753 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9754 let chanmon_cfgs = create_chanmon_cfgs(2);
9755 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9756 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9757 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9759 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9761 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9762 .with_features(channelmanager::provided_invoice_features());
9763 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9765 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9768 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9769 check_added_monitors!(nodes[0], 1);
9770 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9771 assert_eq!(events.len(), 1);
9772 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9773 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9774 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9776 expect_pending_htlcs_forwardable!(nodes[1]);
9777 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9780 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9781 check_added_monitors!(nodes[0], 1);
9782 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9783 assert_eq!(events.len(), 1);
9784 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9785 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9786 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9787 // At this point, nodes[1] would notice it has too much value for the payment. It will
9788 // assume the second is a privacy attack (no longer particularly relevant
9789 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9790 // the first HTLC delivered above.
9793 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9794 nodes[1].node.process_pending_htlc_forwards();
9796 if test_for_second_fail_panic {
9797 // Now we go fail back the first HTLC from the user end.
9798 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9800 let expected_destinations = vec![
9801 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9802 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9804 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9805 nodes[1].node.process_pending_htlc_forwards();
9807 check_added_monitors!(nodes[1], 1);
9808 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9809 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9811 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9812 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9813 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9815 let failure_events = nodes[0].node.get_and_clear_pending_events();
9816 assert_eq!(failure_events.len(), 2);
9817 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9818 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9820 // Let the second HTLC fail and claim the first
9821 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9822 nodes[1].node.process_pending_htlc_forwards();
9824 check_added_monitors!(nodes[1], 1);
9825 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9826 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9827 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9829 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9831 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9836 fn test_dup_htlc_second_fail_panic() {
9837 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9838 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9839 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9840 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9841 do_test_dup_htlc_second_rejected(true);
9845 fn test_dup_htlc_second_rejected() {
9846 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9847 // simply reject the second HTLC but are still able to claim the first HTLC.
9848 do_test_dup_htlc_second_rejected(false);
9852 fn test_inconsistent_mpp_params() {
9853 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9854 // such HTLC and allow the second to stay.
9855 let chanmon_cfgs = create_chanmon_cfgs(4);
9856 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9857 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9858 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9860 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9861 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9862 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9863 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());
9865 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9866 .with_features(channelmanager::provided_invoice_features());
9867 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9868 assert_eq!(route.paths.len(), 2);
9869 route.paths.sort_by(|path_a, _| {
9870 // Sort the path so that the path through nodes[1] comes first
9871 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9872 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9874 let payment_params_opt = Some(payment_params);
9876 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9878 let cur_height = nodes[0].best_block_info().1;
9879 let payment_id = PaymentId([42; 32]);
9881 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();
9882 check_added_monitors!(nodes[0], 1);
9884 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9885 assert_eq!(events.len(), 1);
9886 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9888 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9891 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();
9892 check_added_monitors!(nodes[0], 1);
9894 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9895 assert_eq!(events.len(), 1);
9896 let payment_event = SendEvent::from_event(events.pop().unwrap());
9898 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9899 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9901 expect_pending_htlcs_forwardable!(nodes[2]);
9902 check_added_monitors!(nodes[2], 1);
9904 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9905 assert_eq!(events.len(), 1);
9906 let payment_event = SendEvent::from_event(events.pop().unwrap());
9908 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9909 check_added_monitors!(nodes[3], 0);
9910 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9912 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9913 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9914 // post-payment_secrets) and fail back the new HTLC.
9916 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9917 nodes[3].node.process_pending_htlc_forwards();
9918 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9919 nodes[3].node.process_pending_htlc_forwards();
9921 check_added_monitors!(nodes[3], 1);
9923 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9924 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9925 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9927 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 }]);
9928 check_added_monitors!(nodes[2], 1);
9930 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9931 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9932 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9934 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9936 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();
9937 check_added_monitors!(nodes[0], 1);
9939 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9940 assert_eq!(events.len(), 1);
9941 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9943 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9947 fn test_keysend_payments_to_public_node() {
9948 let chanmon_cfgs = create_chanmon_cfgs(2);
9949 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9950 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9951 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9953 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9954 let network_graph = nodes[0].network_graph;
9955 let payer_pubkey = nodes[0].node.get_our_node_id();
9956 let payee_pubkey = nodes[1].node.get_our_node_id();
9957 let route_params = RouteParameters {
9958 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9959 final_value_msat: 10000,
9960 final_cltv_expiry_delta: 40,
9962 let scorer = test_utils::TestScorer::with_penalty(0);
9963 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9964 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9966 let test_preimage = PaymentPreimage([42; 32]);
9967 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9968 check_added_monitors!(nodes[0], 1);
9969 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9970 assert_eq!(events.len(), 1);
9971 let event = events.pop().unwrap();
9972 let path = vec![&nodes[1]];
9973 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9974 claim_payment(&nodes[0], &path, test_preimage);
9978 fn test_keysend_payments_to_private_node() {
9979 let chanmon_cfgs = create_chanmon_cfgs(2);
9980 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9981 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9982 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9984 let payer_pubkey = nodes[0].node.get_our_node_id();
9985 let payee_pubkey = nodes[1].node.get_our_node_id();
9986 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9987 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9989 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9990 let route_params = RouteParameters {
9991 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9992 final_value_msat: 10000,
9993 final_cltv_expiry_delta: 40,
9995 let network_graph = nodes[0].network_graph;
9996 let first_hops = nodes[0].node.list_usable_channels();
9997 let scorer = test_utils::TestScorer::with_penalty(0);
9998 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9999 let route = find_route(
10000 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10001 nodes[0].logger, &scorer, &random_seed_bytes
10004 let test_preimage = PaymentPreimage([42; 32]);
10005 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
10006 check_added_monitors!(nodes[0], 1);
10007 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10008 assert_eq!(events.len(), 1);
10009 let event = events.pop().unwrap();
10010 let path = vec![&nodes[1]];
10011 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10012 claim_payment(&nodes[0], &path, test_preimage);
10016 fn test_double_partial_claim() {
10017 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
10018 // time out, the sender resends only some of the MPP parts, then the user processes the
10019 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10021 let chanmon_cfgs = create_chanmon_cfgs(4);
10022 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10023 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10024 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10026 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10027 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10028 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10029 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10031 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10032 assert_eq!(route.paths.len(), 2);
10033 route.paths.sort_by(|path_a, _| {
10034 // Sort the path so that the path through nodes[1] comes first
10035 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10036 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10039 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10040 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10041 // amount of time to respond to.
10043 // Connect some blocks to time out the payment
10044 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10045 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10047 let failed_destinations = vec![
10048 HTLCDestination::FailedPayment { payment_hash },
10049 HTLCDestination::FailedPayment { payment_hash },
10051 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10053 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10055 // nodes[1] now retries one of the two paths...
10056 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10057 check_added_monitors!(nodes[0], 2);
10059 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10060 assert_eq!(events.len(), 2);
10061 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10063 // At this point nodes[3] has received one half of the payment, and the user goes to handle
10064 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10065 nodes[3].node.claim_funds(payment_preimage);
10066 check_added_monitors!(nodes[3], 0);
10067 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10070 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10071 // Test what happens if a node receives an MPP payment, claims it, but crashes before
10072 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10073 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10074 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10075 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10076 // not have the preimage tied to the still-pending HTLC.
10078 // To get to the correct state, on startup we should propagate the preimage to the
10079 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10080 // receiving the preimage without a state update.
10082 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10083 // definitely claimed.
10084 let chanmon_cfgs = create_chanmon_cfgs(4);
10085 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10086 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10088 let persister: test_utils::TestPersister;
10089 let new_chain_monitor: test_utils::TestChainMonitor;
10090 let nodes_3_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10092 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10094 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10095 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
10096 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;
10097 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;
10099 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10100 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10101 assert_eq!(route.paths.len(), 2);
10102 route.paths.sort_by(|path_a, _| {
10103 // Sort the path so that the path through nodes[1] comes first
10104 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10105 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10108 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10109 check_added_monitors!(nodes[0], 2);
10111 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10112 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10113 assert_eq!(send_events.len(), 2);
10114 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);
10115 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);
10117 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10118 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10119 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10120 if !persist_both_monitors {
10121 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10122 if outpoint.to_channel_id() == chan_id_not_persisted {
10123 assert!(original_monitor.0.is_empty());
10124 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10129 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10130 nodes[3].node.write(&mut original_manager).unwrap();
10132 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10134 nodes[3].node.claim_funds(payment_preimage);
10135 check_added_monitors!(nodes[3], 2);
10136 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10138 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10139 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10140 // with the old ChannelManager.
10141 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10142 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10143 if outpoint.to_channel_id() == chan_id_persisted {
10144 assert!(updated_monitor.0.is_empty());
10145 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10148 // If `persist_both_monitors` is set, get the second monitor here as well
10149 if persist_both_monitors {
10150 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10151 if outpoint.to_channel_id() == chan_id_not_persisted {
10152 assert!(original_monitor.0.is_empty());
10153 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10158 // Now restart nodes[3].
10159 persister = test_utils::TestPersister::new();
10160 let keys_manager = &chanmon_cfgs[3].keys_manager;
10161 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);
10162 nodes[3].chain_monitor = &new_chain_monitor;
10163 let mut monitors = Vec::new();
10164 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10165 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10166 monitors.push(deserialized_monitor);
10169 let config = UserConfig::default();
10170 nodes_3_deserialized = {
10171 let mut channel_monitors = HashMap::new();
10172 for monitor in monitors.iter_mut() {
10173 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10175 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10176 default_config: config,
10178 fee_estimator: node_cfgs[3].fee_estimator,
10179 chain_monitor: nodes[3].chain_monitor,
10180 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10181 logger: nodes[3].logger,
10185 nodes[3].node = &nodes_3_deserialized;
10187 for monitor in monitors {
10188 // On startup the preimage should have been copied into the non-persisted monitor:
10189 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10190 assert_eq!(nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor),
10191 ChannelMonitorUpdateStatus::Completed);
10193 check_added_monitors!(nodes[3], 2);
10195 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10196 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10198 // During deserialization, we should have closed one channel and broadcast its latest
10199 // commitment transaction. We should also still have the original PaymentReceived event we
10200 // never finished processing.
10201 let events = nodes[3].node.get_and_clear_pending_events();
10202 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10203 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10204 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10205 if persist_both_monitors {
10206 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10209 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10210 // ChannelManager prior to handling the original one.
10211 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10212 events[if persist_both_monitors { 3 } else { 2 }]
10214 assert_eq!(payment_hash, our_payment_hash);
10215 } else { panic!(); }
10217 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10218 if !persist_both_monitors {
10219 // If one of the two channels is still live, reveal the payment preimage over it.
10221 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10222 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10223 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
10224 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10226 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10227 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10228 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10230 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10232 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10233 // claim should fly.
10234 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10235 check_added_monitors!(nodes[3], 1);
10236 assert_eq!(ds_msgs.len(), 2);
10237 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10239 let cs_updates = match ds_msgs[0] {
10240 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10241 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10242 check_added_monitors!(nodes[2], 1);
10243 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10244 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10245 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10251 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10252 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10253 expect_payment_sent!(nodes[0], payment_preimage);
10258 fn test_partial_claim_before_restart() {
10259 do_test_partial_claim_before_restart(false);
10260 do_test_partial_claim_before_restart(true);
10263 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10264 #[derive(Clone, Copy, PartialEq)]
10265 enum ExposureEvent {
10266 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10268 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10270 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10271 AtUpdateFeeOutbound,
10274 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10275 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10278 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10279 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10280 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10281 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10282 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10283 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10284 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10285 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10287 let chanmon_cfgs = create_chanmon_cfgs(2);
10288 let mut config = test_default_channel_config();
10289 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10290 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10291 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10292 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10294 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10295 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10296 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10297 open_channel.max_accepted_htlcs = 60;
10299 open_channel.dust_limit_satoshis = 546;
10301 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
10302 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10303 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
10305 let opt_anchors = false;
10307 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10310 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10311 chan.holder_dust_limit_satoshis = 546;
10315 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10316 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()));
10317 check_added_monitors!(nodes[1], 1);
10319 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()));
10320 check_added_monitors!(nodes[0], 1);
10322 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10323 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10324 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10326 let dust_buffer_feerate = {
10327 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10328 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10329 chan.get_dust_buffer_feerate(None) as u64
10331 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;
10332 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10334 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;
10335 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10337 let dust_htlc_on_counterparty_tx: u64 = 25;
10338 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10341 if dust_outbound_balance {
10342 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10343 // Outbound dust balance: 4372 sats
10344 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10345 for i in 0..dust_outbound_htlc_on_holder_tx {
10346 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10347 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10350 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10351 // Inbound dust balance: 4372 sats
10352 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10353 for _ in 0..dust_inbound_htlc_on_holder_tx {
10354 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10358 if dust_outbound_balance {
10359 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10360 // Outbound dust balance: 5000 sats
10361 for i in 0..dust_htlc_on_counterparty_tx {
10362 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_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: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10367 // Inbound dust balance: 5000 sats
10368 for _ in 0..dust_htlc_on_counterparty_tx {
10369 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10374 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10375 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10376 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 });
10377 let mut config = UserConfig::default();
10378 // With default dust exposure: 5000 sats
10380 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10381 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10382 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)));
10384 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)));
10386 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10387 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 });
10388 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10389 check_added_monitors!(nodes[1], 1);
10390 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10391 assert_eq!(events.len(), 1);
10392 let payment_event = SendEvent::from_event(events.remove(0));
10393 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10394 // With default dust exposure: 5000 sats
10396 // Outbound dust balance: 6399 sats
10397 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10398 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10399 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);
10401 // Outbound dust balance: 5200 sats
10402 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);
10404 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10405 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10406 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10408 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10409 *feerate_lock = *feerate_lock * 10;
10411 nodes[0].node.timer_tick_occurred();
10412 check_added_monitors!(nodes[0], 1);
10413 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);
10416 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10417 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10418 added_monitors.clear();
10422 fn test_max_dust_htlc_exposure() {
10423 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10424 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10425 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10426 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10427 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10428 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10429 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10430 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10431 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10432 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10433 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10434 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10438 fn test_non_final_funding_tx() {
10439 let chanmon_cfgs = create_chanmon_cfgs(2);
10440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10442 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10444 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10445 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10446 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
10447 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10448 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
10450 let best_height = nodes[0].node.best_block.read().unwrap().height();
10452 let chan_id = *nodes[0].network_chan_count.borrow();
10453 let events = nodes[0].node.get_and_clear_pending_events();
10454 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10455 assert_eq!(events.len(), 1);
10456 let mut tx = match events[0] {
10457 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10458 // Timelock the transaction _beyond_ the best client height + 2.
10459 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10460 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10463 _ => panic!("Unexpected event"),
10465 // Transaction should fail as it's evaluated as non-final for propagation.
10466 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10467 Err(APIError::APIMisuseError { err }) => {
10468 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10473 // However, transaction should be accepted if it's in a +2 headroom from best block.
10474 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10475 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10476 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());