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 chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use 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};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
37 use bitcoin::hash_types::BlockHash;
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
44 use bitcoin::secp256k1::Secp256k1;
45 use bitcoin::secp256k1::{PublicKey,SecretKey};
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
59 fn test_insane_channel_opens() {
60 // Stand up a network of 2 nodes
61 use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
62 let mut cfg = UserConfig::default();
63 cfg.peer_channel_config_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
64 let chanmon_cfgs = create_chanmon_cfgs(2);
65 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
66 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
67 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
69 // Instantiate channel parameters where we push the maximum msats given our
71 let channel_value_sat = 31337; // same as funding satoshis
72 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
73 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
75 // Have node0 initiate a channel to node1 with aforementioned parameters
76 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
78 // Extract the channel open message from node0 to node1
79 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
81 // Test helper that asserts we get the correct error string given a mutator
82 // that supposedly makes the channel open message insane
83 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
84 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
85 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
86 assert_eq!(msg_events.len(), 1);
87 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
88 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
90 &ErrorAction::SendErrorMessage { .. } => {
91 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
93 _ => panic!("unexpected event!"),
95 } else { assert!(false); }
98 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
100 // Test all mutations that would make the channel open message insane
101 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 });
102 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 });
104 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
106 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 });
108 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
110 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 });
112 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 });
114 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 fn test_funding_exceeds_no_wumbo_limit() {
121 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
123 use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
124 let chanmon_cfgs = create_chanmon_cfgs(2);
125 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126 node_cfgs[1].features = InitFeatures::known().clear_wumbo();
127 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
130 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
131 Err(APIError::APIMisuseError { err }) => {
132 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
138 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
139 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
140 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
141 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
142 // in normal testing, we test it explicitly here.
143 let chanmon_cfgs = create_chanmon_cfgs(2);
144 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
145 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
146 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
148 // Have node0 initiate a channel to node1 with aforementioned parameters
149 let mut push_amt = 100_000_000;
150 let feerate_per_kw = 253;
151 let opt_anchors = false;
152 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
153 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
155 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();
156 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
157 if !send_from_initiator {
158 open_channel_message.channel_reserve_satoshis = 0;
159 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
161 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
163 // Extract the channel accept message from node1 to node0
164 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
165 if send_from_initiator {
166 accept_channel_message.channel_reserve_satoshis = 0;
167 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
169 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
172 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
173 chan.holder_selected_channel_reserve_satoshis = 0;
174 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
177 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
178 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
179 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
181 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
182 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
183 if send_from_initiator {
184 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
185 // Note that for outbound channels we have to consider the commitment tx fee and the
186 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
187 // well as an additional HTLC.
188 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
190 send_payment(&nodes[1], &[&nodes[0]], push_amt);
195 fn test_counterparty_no_reserve() {
196 do_test_counterparty_no_reserve(true);
197 do_test_counterparty_no_reserve(false);
201 fn test_async_inbound_update_fee() {
202 let chanmon_cfgs = create_chanmon_cfgs(2);
203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
205 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
206 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
209 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
213 // send (1) commitment_signed -.
214 // <- update_add_htlc/commitment_signed
215 // send (2) RAA (awaiting remote revoke) -.
216 // (1) commitment_signed is delivered ->
217 // .- send (3) RAA (awaiting remote revoke)
218 // (2) RAA is delivered ->
219 // .- send (4) commitment_signed
220 // <- (3) RAA is delivered
221 // send (5) commitment_signed -.
222 // <- (4) commitment_signed is delivered
224 // (5) commitment_signed is delivered ->
226 // (6) RAA is delivered ->
228 // First nodes[0] generates an update_fee
230 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
233 nodes[0].node.timer_tick_occurred();
234 check_added_monitors!(nodes[0], 1);
236 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
237 assert_eq!(events_0.len(), 1);
238 let (update_msg, commitment_signed) = match events_0[0] { // (1)
239 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
240 (update_fee.as_ref(), commitment_signed)
242 _ => panic!("Unexpected event"),
245 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
247 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
248 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
249 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
250 check_added_monitors!(nodes[1], 1);
252 let payment_event = {
253 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
254 assert_eq!(events_1.len(), 1);
255 SendEvent::from_event(events_1.remove(0))
257 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
258 assert_eq!(payment_event.msgs.len(), 1);
260 // ...now when the messages get delivered everyone should be happy
261 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
262 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
263 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
264 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
265 check_added_monitors!(nodes[0], 1);
267 // deliver(1), generate (3):
268 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
269 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
270 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
271 check_added_monitors!(nodes[1], 1);
273 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
274 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
275 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
276 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
277 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
278 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
279 assert!(bs_update.update_fee.is_none()); // (4)
280 check_added_monitors!(nodes[1], 1);
282 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
283 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
284 assert!(as_update.update_add_htlcs.is_empty()); // (5)
285 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
286 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
287 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
288 assert!(as_update.update_fee.is_none()); // (5)
289 check_added_monitors!(nodes[0], 1);
291 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
292 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
293 // only (6) so get_event_msg's assert(len == 1) passes
294 check_added_monitors!(nodes[0], 1);
296 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
297 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
298 check_added_monitors!(nodes[1], 1);
300 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
301 check_added_monitors!(nodes[0], 1);
303 let events_2 = nodes[0].node.get_and_clear_pending_events();
304 assert_eq!(events_2.len(), 1);
306 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
307 _ => panic!("Unexpected event"),
310 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
311 check_added_monitors!(nodes[1], 1);
315 fn test_update_fee_unordered_raa() {
316 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
317 // crash in an earlier version of the update_fee patch)
318 let chanmon_cfgs = create_chanmon_cfgs(2);
319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
322 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
325 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
327 // First nodes[0] generates an update_fee
329 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
332 nodes[0].node.timer_tick_occurred();
333 check_added_monitors!(nodes[0], 1);
335 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
336 assert_eq!(events_0.len(), 1);
337 let update_msg = match events_0[0] { // (1)
338 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
341 _ => panic!("Unexpected event"),
344 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
346 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
347 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
348 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
349 check_added_monitors!(nodes[1], 1);
351 let payment_event = {
352 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
353 assert_eq!(events_1.len(), 1);
354 SendEvent::from_event(events_1.remove(0))
356 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
357 assert_eq!(payment_event.msgs.len(), 1);
359 // ...now when the messages get delivered everyone should be happy
360 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
361 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
362 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
363 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
364 check_added_monitors!(nodes[0], 1);
366 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
367 check_added_monitors!(nodes[1], 1);
369 // We can't continue, sadly, because our (1) now has a bogus signature
373 fn test_multi_flight_update_fee() {
374 let chanmon_cfgs = create_chanmon_cfgs(2);
375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
377 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
378 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
381 // update_fee/commitment_signed ->
382 // .- send (1) RAA and (2) commitment_signed
383 // update_fee (never committed) ->
385 // We have to manually generate the above update_fee, it is allowed by the protocol but we
386 // don't track which updates correspond to which revoke_and_ack responses so we're in
387 // AwaitingRAA mode and will not generate the update_fee yet.
388 // <- (1) RAA delivered
389 // (3) is generated and send (4) CS -.
390 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
391 // know the per_commitment_point to use for it.
392 // <- (2) commitment_signed delivered
394 // B should send no response here
395 // (4) commitment_signed delivered ->
396 // <- RAA/commitment_signed delivered
399 // First nodes[0] generates an update_fee
402 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
403 initial_feerate = *feerate_lock;
404 *feerate_lock = initial_feerate + 20;
406 nodes[0].node.timer_tick_occurred();
407 check_added_monitors!(nodes[0], 1);
409 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
410 assert_eq!(events_0.len(), 1);
411 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
412 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
413 (update_fee.as_ref().unwrap(), commitment_signed)
415 _ => panic!("Unexpected event"),
418 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
419 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
420 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
421 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
422 check_added_monitors!(nodes[1], 1);
424 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
427 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
428 *feerate_lock = initial_feerate + 40;
430 nodes[0].node.timer_tick_occurred();
431 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
432 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
434 // Create the (3) update_fee message that nodes[0] will generate before it does...
435 let mut update_msg_2 = msgs::UpdateFee {
436 channel_id: update_msg_1.channel_id.clone(),
437 feerate_per_kw: (initial_feerate + 30) as u32,
440 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
442 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
444 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
446 // Deliver (1), generating (3) and (4)
447 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
448 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
449 check_added_monitors!(nodes[0], 1);
450 assert!(as_second_update.update_add_htlcs.is_empty());
451 assert!(as_second_update.update_fulfill_htlcs.is_empty());
452 assert!(as_second_update.update_fail_htlcs.is_empty());
453 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
454 // Check that the update_fee newly generated matches what we delivered:
455 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
456 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
458 // Deliver (2) commitment_signed
459 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
460 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
461 check_added_monitors!(nodes[0], 1);
462 // No commitment_signed so get_event_msg's assert(len == 1) passes
464 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
465 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
466 check_added_monitors!(nodes[1], 1);
469 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
470 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
471 check_added_monitors!(nodes[1], 1);
473 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
474 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
475 check_added_monitors!(nodes[0], 1);
477 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
478 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
479 // No commitment_signed so get_event_msg's assert(len == 1) passes
480 check_added_monitors!(nodes[0], 1);
482 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
483 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
484 check_added_monitors!(nodes[1], 1);
487 fn do_test_sanity_on_in_flight_opens(steps: u8) {
488 // Previously, we had issues deserializing channels when we hadn't connected the first block
489 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
490 // serialization round-trips and simply do steps towards opening a channel and then drop the
493 let chanmon_cfgs = create_chanmon_cfgs(2);
494 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
495 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
496 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
498 if steps & 0b1000_0000 != 0{
500 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
503 connect_block(&nodes[0], &block);
504 connect_block(&nodes[1], &block);
507 if steps & 0x0f == 0 { return; }
508 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
509 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
511 if steps & 0x0f == 1 { return; }
512 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
513 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
515 if steps & 0x0f == 2 { return; }
516 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
518 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
520 if steps & 0x0f == 3 { return; }
521 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
522 check_added_monitors!(nodes[0], 0);
523 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
525 if steps & 0x0f == 4 { return; }
526 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
528 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
529 assert_eq!(added_monitors.len(), 1);
530 assert_eq!(added_monitors[0].0, funding_output);
531 added_monitors.clear();
533 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
535 if steps & 0x0f == 5 { return; }
536 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
538 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
539 assert_eq!(added_monitors.len(), 1);
540 assert_eq!(added_monitors[0].0, funding_output);
541 added_monitors.clear();
544 let events_4 = nodes[0].node.get_and_clear_pending_events();
545 assert_eq!(events_4.len(), 0);
547 if steps & 0x0f == 6 { return; }
548 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
550 if steps & 0x0f == 7 { return; }
551 confirm_transaction_at(&nodes[0], &tx, 2);
552 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
553 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
557 fn test_sanity_on_in_flight_opens() {
558 do_test_sanity_on_in_flight_opens(0);
559 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
560 do_test_sanity_on_in_flight_opens(1);
561 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
562 do_test_sanity_on_in_flight_opens(2);
563 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
564 do_test_sanity_on_in_flight_opens(3);
565 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
566 do_test_sanity_on_in_flight_opens(4);
567 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
568 do_test_sanity_on_in_flight_opens(5);
569 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
570 do_test_sanity_on_in_flight_opens(6);
571 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
572 do_test_sanity_on_in_flight_opens(7);
573 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
574 do_test_sanity_on_in_flight_opens(8);
575 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
579 fn test_update_fee_vanilla() {
580 let chanmon_cfgs = create_chanmon_cfgs(2);
581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
583 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
584 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
587 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
590 nodes[0].node.timer_tick_occurred();
591 check_added_monitors!(nodes[0], 1);
593 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
594 assert_eq!(events_0.len(), 1);
595 let (update_msg, commitment_signed) = match events_0[0] {
596 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 } } => {
597 (update_fee.as_ref(), commitment_signed)
599 _ => panic!("Unexpected event"),
601 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
603 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
604 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
605 check_added_monitors!(nodes[1], 1);
607 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
608 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
609 check_added_monitors!(nodes[0], 1);
611 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
612 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
613 // No commitment_signed so get_event_msg's assert(len == 1) passes
614 check_added_monitors!(nodes[0], 1);
616 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
617 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
618 check_added_monitors!(nodes[1], 1);
622 fn test_update_fee_that_funder_cannot_afford() {
623 let chanmon_cfgs = create_chanmon_cfgs(2);
624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
626 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
627 let channel_value = 5000;
629 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
630 let channel_id = chan.2;
631 let secp_ctx = Secp256k1::new();
632 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
634 let opt_anchors = false;
636 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
637 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
638 // calculate two different feerates here - the expected local limit as well as the expected
640 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;
641 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
643 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
644 *feerate_lock = feerate;
646 nodes[0].node.timer_tick_occurred();
647 check_added_monitors!(nodes[0], 1);
648 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
650 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
652 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
654 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
656 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
658 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
659 assert_eq!(commitment_tx.output.len(), 2);
660 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
661 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
662 actual_fee = channel_value - actual_fee;
663 assert_eq!(total_fee, actual_fee);
667 // Increment the feerate by a small constant, accounting for rounding errors
668 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
671 nodes[0].node.timer_tick_occurred();
672 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
673 check_added_monitors!(nodes[0], 0);
675 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
677 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
678 // needed to sign the new commitment tx and (2) sign the new commitment tx.
679 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
680 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
681 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
682 let chan_signer = local_chan.get_signer();
683 let pubkeys = chan_signer.pubkeys();
684 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
685 pubkeys.funding_pubkey)
687 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
688 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
689 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
690 let chan_signer = remote_chan.get_signer();
691 let pubkeys = chan_signer.pubkeys();
692 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
693 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
694 pubkeys.funding_pubkey)
697 // Assemble the set of keys we can use for signatures for our commitment_signed message.
698 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
699 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
702 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
703 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
704 let local_chan_signer = local_chan.get_signer();
705 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
706 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
707 INITIAL_COMMITMENT_NUMBER - 1,
709 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
710 opt_anchors, local_funding, remote_funding,
711 commit_tx_keys.clone(),
712 non_buffer_feerate + 4,
714 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
716 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
719 let commit_signed_msg = msgs::CommitmentSigned {
722 htlc_signatures: res.1
725 let update_fee = msgs::UpdateFee {
727 feerate_per_kw: non_buffer_feerate + 4,
730 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
732 //While producing the commitment_signed response after handling a received update_fee request the
733 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
734 //Should produce and error.
735 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
736 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
737 check_added_monitors!(nodes[1], 1);
738 check_closed_broadcast!(nodes[1], true);
739 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
743 fn test_update_fee_with_fundee_update_add_htlc() {
744 let chanmon_cfgs = create_chanmon_cfgs(2);
745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
747 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
748 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
751 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
754 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
757 nodes[0].node.timer_tick_occurred();
758 check_added_monitors!(nodes[0], 1);
760 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
761 assert_eq!(events_0.len(), 1);
762 let (update_msg, commitment_signed) = match events_0[0] {
763 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 } } => {
764 (update_fee.as_ref(), commitment_signed)
766 _ => panic!("Unexpected event"),
768 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
769 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
770 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
771 check_added_monitors!(nodes[1], 1);
773 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
775 // nothing happens since node[1] is in AwaitingRemoteRevoke
776 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
778 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
779 assert_eq!(added_monitors.len(), 0);
780 added_monitors.clear();
782 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
783 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
784 // node[1] has nothing to do
786 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
787 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
788 check_added_monitors!(nodes[0], 1);
790 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
791 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
792 // No commitment_signed so get_event_msg's assert(len == 1) passes
793 check_added_monitors!(nodes[0], 1);
794 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
795 check_added_monitors!(nodes[1], 1);
796 // AwaitingRemoteRevoke ends here
798 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
800 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
801 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
802 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
803 assert_eq!(commitment_update.update_fee.is_none(), true);
805 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
806 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
807 check_added_monitors!(nodes[0], 1);
808 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
810 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
811 check_added_monitors!(nodes[1], 1);
812 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
814 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
815 check_added_monitors!(nodes[1], 1);
816 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
817 // No commitment_signed so get_event_msg's assert(len == 1) passes
819 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
820 check_added_monitors!(nodes[0], 1);
821 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
823 expect_pending_htlcs_forwardable!(nodes[0]);
825 let events = nodes[0].node.get_and_clear_pending_events();
826 assert_eq!(events.len(), 1);
828 Event::PaymentReceived { .. } => { },
829 _ => panic!("Unexpected event"),
832 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
834 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
835 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
836 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
837 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
838 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
842 fn test_update_fee() {
843 let chanmon_cfgs = create_chanmon_cfgs(2);
844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
845 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
846 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
847 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
848 let channel_id = chan.2;
851 // (1) update_fee/commitment_signed ->
852 // <- (2) revoke_and_ack
853 // .- send (3) commitment_signed
854 // (4) update_fee/commitment_signed ->
855 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
856 // <- (3) commitment_signed delivered
857 // send (6) revoke_and_ack -.
858 // <- (5) deliver revoke_and_ack
859 // (6) deliver revoke_and_ack ->
860 // .- send (7) commitment_signed in response to (4)
861 // <- (7) deliver commitment_signed
864 // Create and deliver (1)...
867 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
868 feerate = *feerate_lock;
869 *feerate_lock = feerate + 20;
871 nodes[0].node.timer_tick_occurred();
872 check_added_monitors!(nodes[0], 1);
874 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
875 assert_eq!(events_0.len(), 1);
876 let (update_msg, commitment_signed) = match events_0[0] {
877 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 } } => {
878 (update_fee.as_ref(), commitment_signed)
880 _ => panic!("Unexpected event"),
882 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
884 // Generate (2) and (3):
885 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
886 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
887 check_added_monitors!(nodes[1], 1);
890 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
891 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
892 check_added_monitors!(nodes[0], 1);
894 // Create and deliver (4)...
896 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897 *feerate_lock = feerate + 30;
899 nodes[0].node.timer_tick_occurred();
900 check_added_monitors!(nodes[0], 1);
901 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
902 assert_eq!(events_0.len(), 1);
903 let (update_msg, commitment_signed) = match events_0[0] {
904 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 } } => {
905 (update_fee.as_ref(), commitment_signed)
907 _ => panic!("Unexpected event"),
910 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
911 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
912 check_added_monitors!(nodes[1], 1);
914 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
915 // No commitment_signed so get_event_msg's assert(len == 1) passes
917 // Handle (3), creating (6):
918 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
919 check_added_monitors!(nodes[0], 1);
920 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
921 // No commitment_signed so get_event_msg's assert(len == 1) passes
924 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
925 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
926 check_added_monitors!(nodes[0], 1);
928 // Deliver (6), creating (7):
929 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
930 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
931 assert!(commitment_update.update_add_htlcs.is_empty());
932 assert!(commitment_update.update_fulfill_htlcs.is_empty());
933 assert!(commitment_update.update_fail_htlcs.is_empty());
934 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
935 assert!(commitment_update.update_fee.is_none());
936 check_added_monitors!(nodes[1], 1);
939 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
940 check_added_monitors!(nodes[0], 1);
941 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
942 // No commitment_signed so get_event_msg's assert(len == 1) passes
944 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
945 check_added_monitors!(nodes[1], 1);
946 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
948 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
949 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
950 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
951 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
952 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
956 fn fake_network_test() {
957 // Simple test which builds a network of ChannelManagers, connects them to each other, and
958 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
959 let chanmon_cfgs = create_chanmon_cfgs(4);
960 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
961 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
962 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
964 // Create some initial channels
965 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
966 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
967 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
969 // Rebalance the network a bit by relaying one payment through all the channels...
970 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
971 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
972 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
973 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
975 // Send some more payments
976 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
977 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
978 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
980 // Test failure packets
981 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
982 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
984 // Add a new channel that skips 3
985 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
987 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
988 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
989 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
990 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
991 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
992 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995 // Do some rebalance loop payments, simultaneously
996 let mut hops = Vec::with_capacity(3);
998 pubkey: nodes[2].node.get_our_node_id(),
999 node_features: NodeFeatures::empty(),
1000 short_channel_id: chan_2.0.contents.short_channel_id,
1001 channel_features: ChannelFeatures::empty(),
1003 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1005 hops.push(RouteHop {
1006 pubkey: nodes[3].node.get_our_node_id(),
1007 node_features: NodeFeatures::empty(),
1008 short_channel_id: chan_3.0.contents.short_channel_id,
1009 channel_features: ChannelFeatures::empty(),
1011 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1013 hops.push(RouteHop {
1014 pubkey: nodes[1].node.get_our_node_id(),
1015 node_features: NodeFeatures::known(),
1016 short_channel_id: chan_4.0.contents.short_channel_id,
1017 channel_features: ChannelFeatures::known(),
1019 cltv_expiry_delta: TEST_FINAL_CLTV,
1021 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;
1022 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;
1023 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;
1025 let mut hops = Vec::with_capacity(3);
1026 hops.push(RouteHop {
1027 pubkey: nodes[3].node.get_our_node_id(),
1028 node_features: NodeFeatures::empty(),
1029 short_channel_id: chan_4.0.contents.short_channel_id,
1030 channel_features: ChannelFeatures::empty(),
1032 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1034 hops.push(RouteHop {
1035 pubkey: nodes[2].node.get_our_node_id(),
1036 node_features: NodeFeatures::empty(),
1037 short_channel_id: chan_3.0.contents.short_channel_id,
1038 channel_features: ChannelFeatures::empty(),
1040 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1042 hops.push(RouteHop {
1043 pubkey: nodes[1].node.get_our_node_id(),
1044 node_features: NodeFeatures::known(),
1045 short_channel_id: chan_2.0.contents.short_channel_id,
1046 channel_features: ChannelFeatures::known(),
1048 cltv_expiry_delta: TEST_FINAL_CLTV,
1050 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;
1051 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;
1052 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;
1054 // Claim the rebalances...
1055 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1056 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1058 // Add a duplicate new channel from 2 to 4
1059 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1061 // Send some payments across both channels
1062 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1063 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1064 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1067 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1068 let events = nodes[0].node.get_and_clear_pending_msg_events();
1069 assert_eq!(events.len(), 0);
1070 nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1072 //TODO: Test that routes work again here as we've been notified that the channel is full
1074 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1075 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1076 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1078 // Close down the channels...
1079 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1092 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1097 fn holding_cell_htlc_counting() {
1098 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1099 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1100 // commitment dance rounds.
1101 let chanmon_cfgs = create_chanmon_cfgs(3);
1102 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1103 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1104 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1105 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1106 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1108 let mut payments = Vec::new();
1109 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1110 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1112 payments.push((payment_preimage, payment_hash));
1114 check_added_monitors!(nodes[1], 1);
1116 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1117 assert_eq!(events.len(), 1);
1118 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1119 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1121 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1122 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1124 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1126 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1127 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1132 // This should also be true if we try to forward a payment.
1133 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1135 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1136 check_added_monitors!(nodes[0], 1);
1139 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1140 assert_eq!(events.len(), 1);
1141 let payment_event = SendEvent::from_event(events.pop().unwrap());
1142 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1144 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1145 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1146 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1147 // fails), the second will process the resulting failure and fail the HTLC backward.
1148 expect_pending_htlcs_forwardable!(nodes[1]);
1149 expect_pending_htlcs_forwardable!(nodes[1]);
1150 check_added_monitors!(nodes[1], 1);
1152 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1153 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1154 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1156 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1158 // Now forward all the pending HTLCs and claim them back
1159 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1160 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1161 check_added_monitors!(nodes[2], 1);
1163 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1164 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1165 check_added_monitors!(nodes[1], 1);
1166 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
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_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172 for ref update in as_updates.update_add_htlcs.iter() {
1173 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1175 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1176 check_added_monitors!(nodes[2], 1);
1177 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1178 check_added_monitors!(nodes[2], 1);
1179 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1181 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1182 check_added_monitors!(nodes[1], 1);
1183 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1184 check_added_monitors!(nodes[1], 1);
1185 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1187 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1188 check_added_monitors!(nodes[2], 1);
1190 expect_pending_htlcs_forwardable!(nodes[2]);
1192 let events = nodes[2].node.get_and_clear_pending_events();
1193 assert_eq!(events.len(), payments.len());
1194 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1196 &Event::PaymentReceived { ref payment_hash, .. } => {
1197 assert_eq!(*payment_hash, *hash);
1199 _ => panic!("Unexpected event"),
1203 for (preimage, _) in payments.drain(..) {
1204 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1207 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1211 fn duplicate_htlc_test() {
1212 // Test that we accept duplicate payment_hash HTLCs across the network and that
1213 // claiming/failing them are all separate and don't affect each other
1214 let chanmon_cfgs = create_chanmon_cfgs(6);
1215 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1216 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1217 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1219 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1220 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1221 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1222 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1223 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1224 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1226 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1228 *nodes[0].network_payment_count.borrow_mut() -= 1;
1229 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1231 *nodes[0].network_payment_count.borrow_mut() -= 1;
1232 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1234 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1235 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1236 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1240 fn test_duplicate_htlc_different_direction_onchain() {
1241 // Test that ChannelMonitor doesn't generate 2 preimage txn
1242 // when we have 2 HTLCs with same preimage that go across a node
1243 // in opposite directions, even with the same payment secret.
1244 let chanmon_cfgs = create_chanmon_cfgs(2);
1245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1247 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1249 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1252 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1254 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1256 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1257 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1258 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1260 // Provide preimage to node 0 by claiming payment
1261 nodes[0].node.claim_funds(payment_preimage);
1262 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1263 check_added_monitors!(nodes[0], 1);
1265 // Broadcast node 1 commitment txn
1266 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1268 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1269 let mut has_both_htlcs = 0; // check htlcs match ones committed
1270 for outp in remote_txn[0].output.iter() {
1271 if outp.value == 800_000 / 1000 {
1272 has_both_htlcs += 1;
1273 } else if outp.value == 900_000 / 1000 {
1274 has_both_htlcs += 1;
1277 assert_eq!(has_both_htlcs, 2);
1279 mine_transaction(&nodes[0], &remote_txn[0]);
1280 check_added_monitors!(nodes[0], 1);
1281 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1282 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1284 // Check we only broadcast 1 timeout tx
1285 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286 assert_eq!(claim_txn.len(), 8);
1287 assert_eq!(claim_txn[1], claim_txn[4]);
1288 assert_eq!(claim_txn[2], claim_txn[5]);
1289 check_spends!(claim_txn[1], chan_1.3);
1290 check_spends!(claim_txn[2], claim_txn[1]);
1291 check_spends!(claim_txn[7], claim_txn[1]);
1293 assert_eq!(claim_txn[0].input.len(), 1);
1294 assert_eq!(claim_txn[3].input.len(), 1);
1295 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1297 assert_eq!(claim_txn[0].input.len(), 1);
1298 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1299 check_spends!(claim_txn[0], remote_txn[0]);
1300 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1301 assert_eq!(claim_txn[6].input.len(), 1);
1302 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1303 check_spends!(claim_txn[6], remote_txn[0]);
1304 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1306 let events = nodes[0].node.get_and_clear_pending_msg_events();
1307 assert_eq!(events.len(), 3);
1310 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1311 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1312 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1313 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1315 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, .. } } => {
1316 assert!(update_add_htlcs.is_empty());
1317 assert!(update_fail_htlcs.is_empty());
1318 assert_eq!(update_fulfill_htlcs.len(), 1);
1319 assert!(update_fail_malformed_htlcs.is_empty());
1320 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1322 _ => panic!("Unexpected event"),
1328 fn test_basic_channel_reserve() {
1329 let chanmon_cfgs = create_chanmon_cfgs(2);
1330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1332 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1333 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1335 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1336 let channel_reserve = chan_stat.channel_reserve_msat;
1338 // The 2* and +1 are for the fee spike reserve.
1339 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1340 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1341 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1342 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1344 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1346 &APIError::ChannelUnavailable{ref err} =>
1347 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1348 _ => panic!("Unexpected error variant"),
1351 _ => panic!("Unexpected error variant"),
1353 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1354 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);
1356 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1360 fn test_fee_spike_violation_fails_htlc() {
1361 let chanmon_cfgs = create_chanmon_cfgs(2);
1362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1364 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1365 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1367 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1368 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1369 let secp_ctx = Secp256k1::new();
1370 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1372 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1374 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1375 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1376 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1377 let msg = msgs::UpdateAddHTLC {
1380 amount_msat: htlc_msat,
1381 payment_hash: payment_hash,
1382 cltv_expiry: htlc_cltv,
1383 onion_routing_packet: onion_packet,
1386 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1388 // Now manually create the commitment_signed message corresponding to the update_add
1389 // nodes[0] just sent. In the code for construction of this message, "local" refers
1390 // to the sender of the message, and "remote" refers to the receiver.
1392 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1394 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1396 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1397 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1398 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1399 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1400 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1401 let chan_signer = local_chan.get_signer();
1402 // Make the signer believe we validated another commitment, so we can release the secret
1403 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1405 let pubkeys = chan_signer.pubkeys();
1406 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1407 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1408 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1409 chan_signer.pubkeys().funding_pubkey)
1411 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1412 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1413 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1414 let chan_signer = remote_chan.get_signer();
1415 let pubkeys = chan_signer.pubkeys();
1416 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1417 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1418 chan_signer.pubkeys().funding_pubkey)
1421 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1422 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1423 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1425 // Build the remote commitment transaction so we can sign it, and then later use the
1426 // signature for the commitment_signed message.
1427 let local_chan_balance = 1313;
1429 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1431 amount_msat: 3460001,
1432 cltv_expiry: htlc_cltv,
1434 transaction_output_index: Some(1),
1437 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1440 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1441 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1442 let local_chan_signer = local_chan.get_signer();
1443 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1447 local_chan.opt_anchors(), local_funding, remote_funding,
1448 commit_tx_keys.clone(),
1450 &mut vec![(accepted_htlc_info, ())],
1451 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1453 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1456 let commit_signed_msg = msgs::CommitmentSigned {
1459 htlc_signatures: res.1
1462 // Send the commitment_signed message to the nodes[1].
1463 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1464 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1466 // Send the RAA to nodes[1].
1467 let raa_msg = msgs::RevokeAndACK {
1469 per_commitment_secret: local_secret,
1470 next_per_commitment_point: next_local_point
1472 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1474 let events = nodes[1].node.get_and_clear_pending_msg_events();
1475 assert_eq!(events.len(), 1);
1476 // Make sure the HTLC failed in the way we expect.
1478 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1479 assert_eq!(update_fail_htlcs.len(), 1);
1480 update_fail_htlcs[0].clone()
1482 _ => panic!("Unexpected event"),
1484 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1485 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1487 check_added_monitors!(nodes[1], 2);
1491 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1492 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1493 // Set the fee rate for the channel very high, to the point where the fundee
1494 // sending any above-dust amount would result in a channel reserve violation.
1495 // In this test we check that we would be prevented from sending an HTLC in
1497 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1498 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1499 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1500 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1502 let opt_anchors = false;
1504 let mut push_amt = 100_000_000;
1505 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1506 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1508 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1510 // Sending exactly enough to hit the reserve amount should be accepted
1511 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1512 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1515 // However one more HTLC should be significantly over the reserve amount and fail.
1516 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1517 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1518 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1519 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1520 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);
1524 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1525 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1526 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1529 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1531 let opt_anchors = false;
1533 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1534 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1535 // transaction fee with 0 HTLCs (183 sats)).
1536 let mut push_amt = 100_000_000;
1537 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1538 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1539 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1541 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1542 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1543 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1546 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1547 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1548 let secp_ctx = Secp256k1::new();
1549 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1550 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1551 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1552 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1553 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1554 let msg = msgs::UpdateAddHTLC {
1556 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1557 amount_msat: htlc_msat,
1558 payment_hash: payment_hash,
1559 cltv_expiry: htlc_cltv,
1560 onion_routing_packet: onion_packet,
1563 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1564 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1565 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);
1566 assert_eq!(nodes[0].node.list_channels().len(), 0);
1567 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1568 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1569 check_added_monitors!(nodes[0], 1);
1570 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() });
1574 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1575 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1576 // calculating our commitment transaction fee (this was previously broken).
1577 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1578 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1582 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1584 let opt_anchors = false;
1586 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1587 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1588 // transaction fee with 0 HTLCs (183 sats)).
1589 let mut push_amt = 100_000_000;
1590 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1591 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1592 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1594 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1595 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1596 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1597 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1598 // commitment transaction fee.
1599 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1601 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1602 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1603 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1606 // One more than the dust amt should fail, however.
1607 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1608 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1609 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1613 fn test_chan_init_feerate_unaffordability() {
1614 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1615 // channel reserve and feerate requirements.
1616 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1617 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1618 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1619 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1620 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1622 let opt_anchors = false;
1624 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1626 let mut push_amt = 100_000_000;
1627 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1628 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1629 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1631 // During open, we don't have a "counterparty channel reserve" to check against, so that
1632 // requirement only comes into play on the open_channel handling side.
1633 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1634 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1635 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1636 open_channel_msg.push_msat += 1;
1637 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1639 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1640 assert_eq!(msg_events.len(), 1);
1641 match msg_events[0] {
1642 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1643 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1645 _ => panic!("Unexpected event"),
1650 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1651 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1652 // calculating our counterparty's commitment transaction fee (this was previously broken).
1653 let chanmon_cfgs = create_chanmon_cfgs(2);
1654 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1655 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1656 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1657 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1659 let payment_amt = 46000; // Dust amount
1660 // In the previous code, these first four payments would succeed.
1661 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1667 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1674 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1675 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1676 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1681 let chanmon_cfgs = create_chanmon_cfgs(3);
1682 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1683 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1684 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1685 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1686 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1689 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1690 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1691 let feerate = get_feerate!(nodes[0], chan.2);
1692 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1694 // Add a 2* and +1 for the fee spike reserve.
1695 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1696 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;
1697 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1699 // Add a pending HTLC.
1700 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1701 let payment_event_1 = {
1702 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1703 check_added_monitors!(nodes[0], 1);
1705 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706 assert_eq!(events.len(), 1);
1707 SendEvent::from_event(events.remove(0))
1709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1711 // Attempt to trigger a channel reserve violation --> payment failure.
1712 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1713 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;
1714 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1715 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1717 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1718 let secp_ctx = Secp256k1::new();
1719 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1720 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1721 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1722 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1723 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1724 let msg = msgs::UpdateAddHTLC {
1727 amount_msat: htlc_msat + 1,
1728 payment_hash: our_payment_hash_1,
1729 cltv_expiry: htlc_cltv,
1730 onion_routing_packet: onion_packet,
1733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1734 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1735 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1736 assert_eq!(nodes[1].node.list_channels().len(), 1);
1737 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1738 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1739 check_added_monitors!(nodes[1], 1);
1740 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1744 fn test_inbound_outbound_capacity_is_not_zero() {
1745 let chanmon_cfgs = create_chanmon_cfgs(2);
1746 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1747 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1748 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1749 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1750 let channels0 = node_chanmgrs[0].list_channels();
1751 let channels1 = node_chanmgrs[1].list_channels();
1752 assert_eq!(channels0.len(), 1);
1753 assert_eq!(channels1.len(), 1);
1755 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1756 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1757 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1759 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1760 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1763 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1764 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1768 fn test_channel_reserve_holding_cell_htlcs() {
1769 let chanmon_cfgs = create_chanmon_cfgs(3);
1770 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1771 // When this test was written, the default base fee floated based on the HTLC count.
1772 // It is now fixed, so we simply set the fee to the expected value here.
1773 let mut config = test_default_channel_config();
1774 config.channel_options.forwarding_fee_base_msat = 239;
1775 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1776 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1777 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1778 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1780 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1781 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1783 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1784 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1786 macro_rules! expect_forward {
1788 let mut events = $node.node.get_and_clear_pending_msg_events();
1789 assert_eq!(events.len(), 1);
1790 check_added_monitors!($node, 1);
1791 let payment_event = SendEvent::from_event(events.remove(0));
1796 let feemsat = 239; // set above
1797 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1798 let feerate = get_feerate!(nodes[0], chan_1.2);
1799 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1801 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1803 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1805 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1806 route.paths[0].last_mut().unwrap().fee_msat += 1;
1807 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1808 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1809 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)));
1810 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1811 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);
1814 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1815 // nodes[0]'s wealth
1817 let amt_msat = recv_value_0 + total_fee_msat;
1818 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1819 // Also, ensure that each payment has enough to be over the dust limit to
1820 // ensure it'll be included in each commit tx fee calculation.
1821 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1822 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1823 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1826 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1828 let (stat01_, stat11_, stat12_, stat22_) = (
1829 get_channel_value_stat!(nodes[0], chan_1.2),
1830 get_channel_value_stat!(nodes[1], chan_1.2),
1831 get_channel_value_stat!(nodes[1], chan_2.2),
1832 get_channel_value_stat!(nodes[2], chan_2.2),
1835 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1836 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1837 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1838 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1839 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1842 // adding pending output.
1843 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1844 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1845 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1846 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1847 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1848 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1849 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1850 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1851 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1853 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1854 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1855 let amt_msat_1 = recv_value_1 + total_fee_msat;
1857 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);
1858 let payment_event_1 = {
1859 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1860 check_added_monitors!(nodes[0], 1);
1862 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1863 assert_eq!(events.len(), 1);
1864 SendEvent::from_event(events.remove(0))
1866 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1868 // channel reserve test with htlc pending output > 0
1869 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1871 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1872 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1873 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1874 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1877 // split the rest to test holding cell
1878 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1879 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1880 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1881 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1883 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1884 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);
1887 // now see if they go through on both sides
1888 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);
1889 // but this will stuck in the holding cell
1890 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1891 check_added_monitors!(nodes[0], 0);
1892 let events = nodes[0].node.get_and_clear_pending_events();
1893 assert_eq!(events.len(), 0);
1895 // test with outbound holding cell amount > 0
1897 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1898 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1899 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1900 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1901 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);
1904 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);
1905 // this will also stuck in the holding cell
1906 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1907 check_added_monitors!(nodes[0], 0);
1908 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1909 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1911 // flush the pending htlc
1912 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1913 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1914 check_added_monitors!(nodes[1], 1);
1916 // the pending htlc should be promoted to committed
1917 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1918 check_added_monitors!(nodes[0], 1);
1919 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1921 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1922 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1923 // No commitment_signed so get_event_msg's assert(len == 1) passes
1924 check_added_monitors!(nodes[0], 1);
1926 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1927 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1928 check_added_monitors!(nodes[1], 1);
1930 expect_pending_htlcs_forwardable!(nodes[1]);
1932 let ref payment_event_11 = expect_forward!(nodes[1]);
1933 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1934 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1936 expect_pending_htlcs_forwardable!(nodes[2]);
1937 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1939 // flush the htlcs in the holding cell
1940 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1942 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1943 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1944 expect_pending_htlcs_forwardable!(nodes[1]);
1946 let ref payment_event_3 = expect_forward!(nodes[1]);
1947 assert_eq!(payment_event_3.msgs.len(), 2);
1948 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1949 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1951 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1952 expect_pending_htlcs_forwardable!(nodes[2]);
1954 let events = nodes[2].node.get_and_clear_pending_events();
1955 assert_eq!(events.len(), 2);
1957 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1958 assert_eq!(our_payment_hash_21, *payment_hash);
1959 assert_eq!(recv_value_21, amt);
1961 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1962 assert!(payment_preimage.is_none());
1963 assert_eq!(our_payment_secret_21, *payment_secret);
1965 _ => panic!("expected PaymentPurpose::InvoicePayment")
1968 _ => panic!("Unexpected event"),
1971 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1972 assert_eq!(our_payment_hash_22, *payment_hash);
1973 assert_eq!(recv_value_22, amt);
1975 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1976 assert!(payment_preimage.is_none());
1977 assert_eq!(our_payment_secret_22, *payment_secret);
1979 _ => panic!("expected PaymentPurpose::InvoicePayment")
1982 _ => panic!("Unexpected event"),
1985 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1986 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1987 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1989 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1990 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1991 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1993 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1994 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);
1995 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1996 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1997 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1999 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2000 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2004 fn channel_reserve_in_flight_removes() {
2005 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2006 // can send to its counterparty, but due to update ordering, the other side may not yet have
2007 // considered those HTLCs fully removed.
2008 // This tests that we don't count HTLCs which will not be included in the next remote
2009 // commitment transaction towards the reserve value (as it implies no commitment transaction
2010 // will be generated which violates the remote reserve value).
2011 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2013 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2014 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2015 // you only consider the value of the first HTLC, it may not),
2016 // * start routing a third HTLC from A to B,
2017 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2018 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2019 // * deliver the first fulfill from B
2020 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2022 // * deliver A's response CS and RAA.
2023 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2024 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2025 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2026 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2027 let chanmon_cfgs = create_chanmon_cfgs(2);
2028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2030 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2031 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2033 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2034 // Route the first two HTLCs.
2035 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2036 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2037 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2039 // Start routing the third HTLC (this is just used to get everyone in the right state).
2040 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2042 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2043 check_added_monitors!(nodes[0], 1);
2044 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2045 assert_eq!(events.len(), 1);
2046 SendEvent::from_event(events.remove(0))
2049 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2050 // initial fulfill/CS.
2051 nodes[1].node.claim_funds(payment_preimage_1);
2052 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2053 check_added_monitors!(nodes[1], 1);
2054 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2056 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2057 // remove the second HTLC when we send the HTLC back from B to A.
2058 nodes[1].node.claim_funds(payment_preimage_2);
2059 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2060 check_added_monitors!(nodes[1], 1);
2061 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2063 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2064 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2065 check_added_monitors!(nodes[0], 1);
2066 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2067 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2069 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2070 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2071 check_added_monitors!(nodes[1], 1);
2072 // B is already AwaitingRAA, so cant generate a CS here
2073 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2075 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2076 check_added_monitors!(nodes[1], 1);
2077 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2079 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2080 check_added_monitors!(nodes[0], 1);
2081 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2083 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2084 check_added_monitors!(nodes[1], 1);
2085 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2087 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2088 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2089 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2090 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2091 // on-chain as necessary).
2092 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2093 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2094 check_added_monitors!(nodes[0], 1);
2095 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2096 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2098 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2099 check_added_monitors!(nodes[1], 1);
2100 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2102 expect_pending_htlcs_forwardable!(nodes[1]);
2103 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2105 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2106 // resolve the second HTLC from A's point of view.
2107 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2108 check_added_monitors!(nodes[0], 1);
2109 expect_payment_path_successful!(nodes[0]);
2110 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2112 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2113 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2114 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2116 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2117 check_added_monitors!(nodes[1], 1);
2118 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2119 assert_eq!(events.len(), 1);
2120 SendEvent::from_event(events.remove(0))
2123 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2124 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2125 check_added_monitors!(nodes[0], 1);
2126 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2128 // Now just resolve all the outstanding messages/HTLCs for completeness...
2130 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2131 check_added_monitors!(nodes[1], 1);
2132 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2134 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2135 check_added_monitors!(nodes[1], 1);
2137 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2138 check_added_monitors!(nodes[0], 1);
2139 expect_payment_path_successful!(nodes[0]);
2140 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2142 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2143 check_added_monitors!(nodes[1], 1);
2144 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2147 check_added_monitors!(nodes[0], 1);
2149 expect_pending_htlcs_forwardable!(nodes[0]);
2150 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2152 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2153 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2157 fn channel_monitor_network_test() {
2158 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2159 // tests that ChannelMonitor is able to recover from various states.
2160 let chanmon_cfgs = create_chanmon_cfgs(5);
2161 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2162 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2163 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2165 // Create some initial channels
2166 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2167 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2168 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2169 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2171 // Make sure all nodes are at the same starting height
2172 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2173 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2174 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2175 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2176 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2178 // Rebalance the network a bit by relaying one payment through all the channels...
2179 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
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);
2184 // Simple case with no pending HTLCs:
2185 nodes[1].node.force_close_channel(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2186 check_added_monitors!(nodes[1], 1);
2187 check_closed_broadcast!(nodes[1], true);
2189 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2190 assert_eq!(node_txn.len(), 1);
2191 mine_transaction(&nodes[0], &node_txn[0]);
2192 check_added_monitors!(nodes[0], 1);
2193 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2195 check_closed_broadcast!(nodes[0], true);
2196 assert_eq!(nodes[0].node.list_channels().len(), 0);
2197 assert_eq!(nodes[1].node.list_channels().len(), 1);
2198 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2199 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2201 // One pending HTLC is discarded by the force-close:
2202 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2204 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2205 // broadcasted until we reach the timelock time).
2206 nodes[1].node.force_close_channel(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2207 check_closed_broadcast!(nodes[1], true);
2208 check_added_monitors!(nodes[1], 1);
2210 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2211 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2212 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2213 mine_transaction(&nodes[2], &node_txn[0]);
2214 check_added_monitors!(nodes[2], 1);
2215 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2217 check_closed_broadcast!(nodes[2], true);
2218 assert_eq!(nodes[1].node.list_channels().len(), 0);
2219 assert_eq!(nodes[2].node.list_channels().len(), 1);
2220 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2221 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2223 macro_rules! claim_funds {
2224 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2226 $node.node.claim_funds($preimage);
2227 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2228 check_added_monitors!($node, 1);
2230 let events = $node.node.get_and_clear_pending_msg_events();
2231 assert_eq!(events.len(), 1);
2233 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2234 assert!(update_add_htlcs.is_empty());
2235 assert!(update_fail_htlcs.is_empty());
2236 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2238 _ => panic!("Unexpected event"),
2244 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2245 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2246 nodes[2].node.force_close_channel(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2247 check_added_monitors!(nodes[2], 1);
2248 check_closed_broadcast!(nodes[2], true);
2249 let node2_commitment_txid;
2251 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2252 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2253 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2254 node2_commitment_txid = node_txn[0].txid();
2256 // Claim the payment on nodes[3], giving it knowledge of the preimage
2257 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2258 mine_transaction(&nodes[3], &node_txn[0]);
2259 check_added_monitors!(nodes[3], 1);
2260 check_preimage_claim(&nodes[3], &node_txn);
2262 check_closed_broadcast!(nodes[3], true);
2263 assert_eq!(nodes[2].node.list_channels().len(), 0);
2264 assert_eq!(nodes[3].node.list_channels().len(), 1);
2265 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2266 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2268 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2269 // confusing us in the following tests.
2270 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2272 // One pending HTLC to time out:
2273 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2274 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2277 let (close_chan_update_1, close_chan_update_2) = {
2278 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2279 let events = nodes[3].node.get_and_clear_pending_msg_events();
2280 assert_eq!(events.len(), 2);
2281 let close_chan_update_1 = match events[0] {
2282 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2285 _ => panic!("Unexpected event"),
2288 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2289 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2291 _ => panic!("Unexpected event"),
2293 check_added_monitors!(nodes[3], 1);
2295 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2297 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2298 node_txn.retain(|tx| {
2299 if tx.input[0].previous_output.txid == node2_commitment_txid {
2305 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2307 // Claim the payment on nodes[4], giving it knowledge of the preimage
2308 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2310 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2311 let events = nodes[4].node.get_and_clear_pending_msg_events();
2312 assert_eq!(events.len(), 2);
2313 let close_chan_update_2 = match events[0] {
2314 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2317 _ => panic!("Unexpected event"),
2320 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2321 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2323 _ => panic!("Unexpected event"),
2325 check_added_monitors!(nodes[4], 1);
2326 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2328 mine_transaction(&nodes[4], &node_txn[0]);
2329 check_preimage_claim(&nodes[4], &node_txn);
2330 (close_chan_update_1, close_chan_update_2)
2332 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2333 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2334 assert_eq!(nodes[3].node.list_channels().len(), 0);
2335 assert_eq!(nodes[4].node.list_channels().len(), 0);
2337 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2338 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2339 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2343 fn test_justice_tx() {
2344 // Test justice txn built on revoked HTLC-Success tx, against both sides
2345 let mut alice_config = UserConfig::default();
2346 alice_config.channel_options.announced_channel = true;
2347 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2348 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2349 let mut bob_config = UserConfig::default();
2350 bob_config.channel_options.announced_channel = true;
2351 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2352 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2353 let user_cfgs = [Some(alice_config), Some(bob_config)];
2354 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2355 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2356 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2357 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2358 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2359 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2360 // Create some new channels:
2361 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2363 // A pending HTLC which will be revoked:
2364 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2365 // Get the will-be-revoked local txn from nodes[0]
2366 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2367 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2368 assert_eq!(revoked_local_txn[0].input.len(), 1);
2369 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2370 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2371 assert_eq!(revoked_local_txn[1].input.len(), 1);
2372 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2373 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2374 // Revoke the old state
2375 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2378 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2380 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2381 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2382 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2384 check_spends!(node_txn[0], revoked_local_txn[0]);
2385 node_txn.swap_remove(0);
2386 node_txn.truncate(1);
2388 check_added_monitors!(nodes[1], 1);
2389 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2390 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2392 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2393 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2394 // Verify broadcast of revoked HTLC-timeout
2395 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2396 check_added_monitors!(nodes[0], 1);
2397 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2398 // Broadcast revoked HTLC-timeout on node 1
2399 mine_transaction(&nodes[1], &node_txn[1]);
2400 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2402 get_announce_close_broadcast_events(&nodes, 0, 1);
2404 assert_eq!(nodes[0].node.list_channels().len(), 0);
2405 assert_eq!(nodes[1].node.list_channels().len(), 0);
2407 // We test justice_tx build by A on B's revoked HTLC-Success tx
2408 // Create some new channels:
2409 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2411 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2415 // A pending HTLC which will be revoked:
2416 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2417 // Get the will-be-revoked local txn from B
2418 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2419 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2420 assert_eq!(revoked_local_txn[0].input.len(), 1);
2421 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2422 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2423 // Revoke the old state
2424 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2426 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2428 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2430 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2432 check_spends!(node_txn[0], revoked_local_txn[0]);
2433 node_txn.swap_remove(0);
2435 check_added_monitors!(nodes[0], 1);
2436 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2438 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2439 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2440 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2441 check_added_monitors!(nodes[1], 1);
2442 mine_transaction(&nodes[0], &node_txn[1]);
2443 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2444 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2446 get_announce_close_broadcast_events(&nodes, 0, 1);
2447 assert_eq!(nodes[0].node.list_channels().len(), 0);
2448 assert_eq!(nodes[1].node.list_channels().len(), 0);
2452 fn revoked_output_claim() {
2453 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2454 // transaction is broadcast by its counterparty
2455 let chanmon_cfgs = create_chanmon_cfgs(2);
2456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2458 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2459 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2460 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2461 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2462 assert_eq!(revoked_local_txn.len(), 1);
2463 // Only output is the full channel value back to nodes[0]:
2464 assert_eq!(revoked_local_txn[0].output.len(), 1);
2465 // Send a payment through, updating everyone's latest commitment txn
2466 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2468 // Inform nodes[1] that nodes[0] broadcast a stale tx
2469 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2470 check_added_monitors!(nodes[1], 1);
2471 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2472 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2473 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2475 check_spends!(node_txn[0], revoked_local_txn[0]);
2476 check_spends!(node_txn[1], chan_1.3);
2478 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2479 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2480 get_announce_close_broadcast_events(&nodes, 0, 1);
2481 check_added_monitors!(nodes[0], 1);
2482 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2486 fn claim_htlc_outputs_shared_tx() {
2487 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2488 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2489 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2492 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2494 // Create some new channel:
2495 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2497 // Rebalance the network to generate htlc in the two directions
2498 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2499 // 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
2500 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2501 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2503 // Get the will-be-revoked local txn from node[0]
2504 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2505 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2506 assert_eq!(revoked_local_txn[0].input.len(), 1);
2507 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2508 assert_eq!(revoked_local_txn[1].input.len(), 1);
2509 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2510 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2511 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2513 //Revoke the old state
2514 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2517 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2518 check_added_monitors!(nodes[0], 1);
2519 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2520 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2521 check_added_monitors!(nodes[1], 1);
2522 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2523 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2524 expect_payment_failed!(nodes[1], payment_hash_2, true);
2526 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2527 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2529 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2530 check_spends!(node_txn[0], revoked_local_txn[0]);
2532 let mut witness_lens = BTreeSet::new();
2533 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2534 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2535 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2536 assert_eq!(witness_lens.len(), 3);
2537 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2538 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2539 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2541 // Next nodes[1] broadcasts its current local tx state:
2542 assert_eq!(node_txn[1].input.len(), 1);
2543 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2545 get_announce_close_broadcast_events(&nodes, 0, 1);
2546 assert_eq!(nodes[0].node.list_channels().len(), 0);
2547 assert_eq!(nodes[1].node.list_channels().len(), 0);
2551 fn claim_htlc_outputs_single_tx() {
2552 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2553 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2554 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2555 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2556 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2557 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2559 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2561 // Rebalance the network to generate htlc in the two directions
2562 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2563 // 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
2564 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2565 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2566 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2568 // Get the will-be-revoked local txn from node[0]
2569 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2571 //Revoke the old state
2572 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2575 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2576 check_added_monitors!(nodes[0], 1);
2577 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2578 check_added_monitors!(nodes[1], 1);
2579 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2580 let mut events = nodes[0].node.get_and_clear_pending_events();
2581 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2583 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2584 _ => panic!("Unexpected event"),
2587 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2588 expect_payment_failed!(nodes[1], payment_hash_2, true);
2590 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2591 assert_eq!(node_txn.len(), 9);
2592 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2593 // ChannelManager: local commmitment + local HTLC-timeout (2)
2594 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2595 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2597 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2598 assert_eq!(node_txn[0].input.len(), 1);
2599 check_spends!(node_txn[0], chan_1.3);
2600 assert_eq!(node_txn[1].input.len(), 1);
2601 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2602 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2603 check_spends!(node_txn[1], node_txn[0]);
2605 // Justice transactions are indices 1-2-4
2606 assert_eq!(node_txn[2].input.len(), 1);
2607 assert_eq!(node_txn[3].input.len(), 1);
2608 assert_eq!(node_txn[4].input.len(), 1);
2610 check_spends!(node_txn[2], revoked_local_txn[0]);
2611 check_spends!(node_txn[3], revoked_local_txn[0]);
2612 check_spends!(node_txn[4], revoked_local_txn[0]);
2614 let mut witness_lens = BTreeSet::new();
2615 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2616 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2617 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2618 assert_eq!(witness_lens.len(), 3);
2619 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2620 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2621 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2623 get_announce_close_broadcast_events(&nodes, 0, 1);
2624 assert_eq!(nodes[0].node.list_channels().len(), 0);
2625 assert_eq!(nodes[1].node.list_channels().len(), 0);
2629 fn test_htlc_on_chain_success() {
2630 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2631 // the preimage backward accordingly. So here we test that ChannelManager is
2632 // broadcasting the right event to other nodes in payment path.
2633 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2634 // A --------------------> B ----------------------> C (preimage)
2635 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2636 // commitment transaction was broadcast.
2637 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2639 // B should be able to claim via preimage if A then broadcasts its local tx.
2640 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2641 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2642 // PaymentSent event).
2644 let chanmon_cfgs = create_chanmon_cfgs(3);
2645 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2646 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2647 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2649 // Create some initial channels
2650 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2651 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2653 // Ensure all nodes are at the same height
2654 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2655 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2656 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2657 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2659 // Rebalance the network a bit by relaying one payment through all the channels...
2660 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2661 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2663 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2664 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2666 // Broadcast legit commitment tx from C on B's chain
2667 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2668 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2669 assert_eq!(commitment_tx.len(), 1);
2670 check_spends!(commitment_tx[0], chan_2.3);
2671 nodes[2].node.claim_funds(our_payment_preimage);
2672 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2673 nodes[2].node.claim_funds(our_payment_preimage_2);
2674 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2675 check_added_monitors!(nodes[2], 2);
2676 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2677 assert!(updates.update_add_htlcs.is_empty());
2678 assert!(updates.update_fail_htlcs.is_empty());
2679 assert!(updates.update_fail_malformed_htlcs.is_empty());
2680 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2682 mine_transaction(&nodes[2], &commitment_tx[0]);
2683 check_closed_broadcast!(nodes[2], true);
2684 check_added_monitors!(nodes[2], 1);
2685 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2686 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)
2687 assert_eq!(node_txn.len(), 5);
2688 assert_eq!(node_txn[0], node_txn[3]);
2689 assert_eq!(node_txn[1], node_txn[4]);
2690 assert_eq!(node_txn[2], commitment_tx[0]);
2691 check_spends!(node_txn[0], commitment_tx[0]);
2692 check_spends!(node_txn[1], commitment_tx[0]);
2693 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2694 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2695 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2696 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2697 assert_eq!(node_txn[0].lock_time, 0);
2698 assert_eq!(node_txn[1].lock_time, 0);
2700 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2701 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2702 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2703 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2705 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2706 assert_eq!(added_monitors.len(), 1);
2707 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2708 added_monitors.clear();
2710 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2711 assert_eq!(forwarded_events.len(), 3);
2712 match forwarded_events[0] {
2713 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2714 _ => panic!("Unexpected event"),
2716 let chan_id = Some(chan_1.2);
2717 match forwarded_events[1] {
2718 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2719 assert_eq!(fee_earned_msat, Some(1000));
2720 assert_eq!(prev_channel_id, chan_id);
2721 assert_eq!(claim_from_onchain_tx, true);
2722 assert_eq!(next_channel_id, Some(chan_2.2));
2726 match forwarded_events[2] {
2727 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2728 assert_eq!(fee_earned_msat, Some(1000));
2729 assert_eq!(prev_channel_id, chan_id);
2730 assert_eq!(claim_from_onchain_tx, true);
2731 assert_eq!(next_channel_id, Some(chan_2.2));
2735 let events = nodes[1].node.get_and_clear_pending_msg_events();
2737 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2738 assert_eq!(added_monitors.len(), 2);
2739 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2740 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2741 added_monitors.clear();
2743 assert_eq!(events.len(), 3);
2745 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2746 _ => panic!("Unexpected event"),
2749 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2750 _ => panic!("Unexpected event"),
2754 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, .. } } => {
2755 assert!(update_add_htlcs.is_empty());
2756 assert!(update_fail_htlcs.is_empty());
2757 assert_eq!(update_fulfill_htlcs.len(), 1);
2758 assert!(update_fail_malformed_htlcs.is_empty());
2759 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2761 _ => panic!("Unexpected event"),
2763 macro_rules! check_tx_local_broadcast {
2764 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2765 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2766 assert_eq!(node_txn.len(), 3);
2767 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2768 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2769 check_spends!(node_txn[1], $commitment_tx);
2770 check_spends!(node_txn[2], $commitment_tx);
2771 assert_ne!(node_txn[1].lock_time, 0);
2772 assert_ne!(node_txn[2].lock_time, 0);
2774 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2775 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2776 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2777 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2779 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2780 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2781 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2782 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2784 check_spends!(node_txn[0], $chan_tx);
2785 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2789 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2790 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2791 // timeout-claim of the output that nodes[2] just claimed via success.
2792 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2794 // Broadcast legit commitment tx from A on B's chain
2795 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2796 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2797 check_spends!(node_a_commitment_tx[0], chan_1.3);
2798 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2799 check_closed_broadcast!(nodes[1], true);
2800 check_added_monitors!(nodes[1], 1);
2801 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2802 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2803 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2804 let commitment_spend =
2805 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2806 check_spends!(node_txn[1], commitment_tx[0]);
2807 check_spends!(node_txn[2], commitment_tx[0]);
2808 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2811 check_spends!(node_txn[0], commitment_tx[0]);
2812 check_spends!(node_txn[1], commitment_tx[0]);
2813 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2817 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2818 assert_eq!(commitment_spend.input.len(), 2);
2819 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2820 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2821 assert_eq!(commitment_spend.lock_time, 0);
2822 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2823 check_spends!(node_txn[3], chan_1.3);
2824 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2825 check_spends!(node_txn[4], node_txn[3]);
2826 check_spends!(node_txn[5], node_txn[3]);
2827 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2828 // we already checked the same situation with A.
2830 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2831 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2832 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2833 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2834 check_closed_broadcast!(nodes[0], true);
2835 check_added_monitors!(nodes[0], 1);
2836 let events = nodes[0].node.get_and_clear_pending_events();
2837 assert_eq!(events.len(), 5);
2838 let mut first_claimed = false;
2839 for event in events {
2841 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2842 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2843 assert!(!first_claimed);
2844 first_claimed = true;
2846 assert_eq!(payment_preimage, our_payment_preimage_2);
2847 assert_eq!(payment_hash, payment_hash_2);
2850 Event::PaymentPathSuccessful { .. } => {},
2851 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2852 _ => panic!("Unexpected event"),
2855 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2858 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2859 // Test that in case of a unilateral close onchain, we detect the state of output and
2860 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2861 // broadcasting the right event to other nodes in payment path.
2862 // A ------------------> B ----------------------> C (timeout)
2863 // B's commitment tx C's commitment tx
2865 // B's HTLC timeout tx B's timeout tx
2867 let chanmon_cfgs = create_chanmon_cfgs(3);
2868 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2869 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2870 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2871 *nodes[0].connect_style.borrow_mut() = connect_style;
2872 *nodes[1].connect_style.borrow_mut() = connect_style;
2873 *nodes[2].connect_style.borrow_mut() = connect_style;
2875 // Create some intial channels
2876 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2877 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2879 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2880 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2881 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2883 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2885 // Broadcast legit commitment tx from C on B's chain
2886 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2887 check_spends!(commitment_tx[0], chan_2.3);
2888 nodes[2].node.fail_htlc_backwards(&payment_hash);
2889 check_added_monitors!(nodes[2], 0);
2890 expect_pending_htlcs_forwardable!(nodes[2]);
2891 check_added_monitors!(nodes[2], 1);
2893 let events = nodes[2].node.get_and_clear_pending_msg_events();
2894 assert_eq!(events.len(), 1);
2896 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, .. } } => {
2897 assert!(update_add_htlcs.is_empty());
2898 assert!(!update_fail_htlcs.is_empty());
2899 assert!(update_fulfill_htlcs.is_empty());
2900 assert!(update_fail_malformed_htlcs.is_empty());
2901 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2903 _ => panic!("Unexpected event"),
2905 mine_transaction(&nodes[2], &commitment_tx[0]);
2906 check_closed_broadcast!(nodes[2], true);
2907 check_added_monitors!(nodes[2], 1);
2908 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2909 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2910 assert_eq!(node_txn.len(), 1);
2911 check_spends!(node_txn[0], chan_2.3);
2912 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2914 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2915 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2916 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2917 mine_transaction(&nodes[1], &commitment_tx[0]);
2918 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2921 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2922 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2923 assert_eq!(node_txn[0], node_txn[3]);
2924 assert_eq!(node_txn[1], node_txn[4]);
2926 check_spends!(node_txn[2], commitment_tx[0]);
2927 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2929 check_spends!(node_txn[0], chan_2.3);
2930 check_spends!(node_txn[1], node_txn[0]);
2931 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2932 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2934 timeout_tx = node_txn[2].clone();
2938 mine_transaction(&nodes[1], &timeout_tx);
2939 check_added_monitors!(nodes[1], 1);
2940 check_closed_broadcast!(nodes[1], true);
2942 // B will rebroadcast a fee-bumped timeout transaction here.
2943 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2944 assert_eq!(node_txn.len(), 1);
2945 check_spends!(node_txn[0], commitment_tx[0]);
2948 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2950 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2951 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2952 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2953 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2954 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2955 if node_txn.len() == 1 {
2956 check_spends!(node_txn[0], chan_2.3);
2958 assert_eq!(node_txn.len(), 0);
2962 expect_pending_htlcs_forwardable!(nodes[1]);
2963 check_added_monitors!(nodes[1], 1);
2964 let events = nodes[1].node.get_and_clear_pending_msg_events();
2965 assert_eq!(events.len(), 1);
2967 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, .. } } => {
2968 assert!(update_add_htlcs.is_empty());
2969 assert!(!update_fail_htlcs.is_empty());
2970 assert!(update_fulfill_htlcs.is_empty());
2971 assert!(update_fail_malformed_htlcs.is_empty());
2972 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2974 _ => panic!("Unexpected event"),
2977 // Broadcast legit commitment tx from B on A's chain
2978 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2979 check_spends!(commitment_tx[0], chan_1.3);
2981 mine_transaction(&nodes[0], &commitment_tx[0]);
2982 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2984 check_closed_broadcast!(nodes[0], true);
2985 check_added_monitors!(nodes[0], 1);
2986 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2987 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2988 assert_eq!(node_txn.len(), 2);
2989 check_spends!(node_txn[0], chan_1.3);
2990 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2991 check_spends!(node_txn[1], commitment_tx[0]);
2992 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2996 fn test_htlc_on_chain_timeout() {
2997 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2998 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2999 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3003 fn test_simple_commitment_revoked_fail_backward() {
3004 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3005 // and fail backward accordingly.
3007 let chanmon_cfgs = create_chanmon_cfgs(3);
3008 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3009 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3010 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3012 // Create some initial channels
3013 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3014 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3016 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3017 // Get the will-be-revoked local txn from nodes[2]
3018 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3019 // Revoke the old state
3020 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3022 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3024 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3025 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3026 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3027 check_added_monitors!(nodes[1], 1);
3028 check_closed_broadcast!(nodes[1], true);
3030 expect_pending_htlcs_forwardable!(nodes[1]);
3031 check_added_monitors!(nodes[1], 1);
3032 let events = nodes[1].node.get_and_clear_pending_msg_events();
3033 assert_eq!(events.len(), 1);
3035 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, .. } } => {
3036 assert!(update_add_htlcs.is_empty());
3037 assert_eq!(update_fail_htlcs.len(), 1);
3038 assert!(update_fulfill_htlcs.is_empty());
3039 assert!(update_fail_malformed_htlcs.is_empty());
3040 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3042 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3043 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3044 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3046 _ => panic!("Unexpected event"),
3050 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3051 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3052 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3053 // commitment transaction anymore.
3054 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3055 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3056 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3057 // technically disallowed and we should probably handle it reasonably.
3058 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3059 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3061 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3062 // commitment_signed (implying it will be in the latest remote commitment transaction).
3063 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3064 // and once they revoke the previous commitment transaction (allowing us to send a new
3065 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3066 let chanmon_cfgs = create_chanmon_cfgs(3);
3067 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3068 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3069 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3071 // Create some initial channels
3072 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3073 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3075 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 });
3076 // Get the will-be-revoked local txn from nodes[2]
3077 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3078 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3079 // Revoke the old state
3080 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3082 let value = if use_dust {
3083 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3084 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3085 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3088 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3089 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3090 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3092 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3093 expect_pending_htlcs_forwardable!(nodes[2]);
3094 check_added_monitors!(nodes[2], 1);
3095 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3096 assert!(updates.update_add_htlcs.is_empty());
3097 assert!(updates.update_fulfill_htlcs.is_empty());
3098 assert!(updates.update_fail_malformed_htlcs.is_empty());
3099 assert_eq!(updates.update_fail_htlcs.len(), 1);
3100 assert!(updates.update_fee.is_none());
3101 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3102 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3103 // Drop the last RAA from 3 -> 2
3105 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3106 expect_pending_htlcs_forwardable!(nodes[2]);
3107 check_added_monitors!(nodes[2], 1);
3108 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3109 assert!(updates.update_add_htlcs.is_empty());
3110 assert!(updates.update_fulfill_htlcs.is_empty());
3111 assert!(updates.update_fail_malformed_htlcs.is_empty());
3112 assert_eq!(updates.update_fail_htlcs.len(), 1);
3113 assert!(updates.update_fee.is_none());
3114 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3115 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3116 check_added_monitors!(nodes[1], 1);
3117 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3118 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3119 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3120 check_added_monitors!(nodes[2], 1);
3122 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3123 expect_pending_htlcs_forwardable!(nodes[2]);
3124 check_added_monitors!(nodes[2], 1);
3125 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3126 assert!(updates.update_add_htlcs.is_empty());
3127 assert!(updates.update_fulfill_htlcs.is_empty());
3128 assert!(updates.update_fail_malformed_htlcs.is_empty());
3129 assert_eq!(updates.update_fail_htlcs.len(), 1);
3130 assert!(updates.update_fee.is_none());
3131 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3132 // At this point first_payment_hash has dropped out of the latest two commitment
3133 // transactions that nodes[1] is tracking...
3134 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3135 check_added_monitors!(nodes[1], 1);
3136 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3137 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3138 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3139 check_added_monitors!(nodes[2], 1);
3141 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3142 // on nodes[2]'s RAA.
3143 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3144 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3145 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3146 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3147 check_added_monitors!(nodes[1], 0);
3150 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3151 // One monitor for the new revocation preimage, no second on as we won't generate a new
3152 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3153 check_added_monitors!(nodes[1], 1);
3154 let events = nodes[1].node.get_and_clear_pending_events();
3155 assert_eq!(events.len(), 1);
3157 Event::PendingHTLCsForwardable { .. } => { },
3158 _ => panic!("Unexpected event"),
3160 // Deliberately don't process the pending fail-back so they all fail back at once after
3161 // block connection just like the !deliver_bs_raa case
3164 let mut failed_htlcs = HashSet::new();
3165 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3167 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3168 check_added_monitors!(nodes[1], 1);
3169 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3170 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3172 let events = nodes[1].node.get_and_clear_pending_events();
3173 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3175 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3176 _ => panic!("Unexepected event"),
3179 Event::PaymentPathFailed { ref payment_hash, .. } => {
3180 assert_eq!(*payment_hash, fourth_payment_hash);
3182 _ => panic!("Unexpected event"),
3184 if !deliver_bs_raa {
3186 Event::PaymentFailed { ref payment_hash, .. } => {
3187 assert_eq!(*payment_hash, fourth_payment_hash);
3189 _ => panic!("Unexpected event"),
3192 Event::PendingHTLCsForwardable { .. } => { },
3193 _ => panic!("Unexpected event"),
3196 nodes[1].node.process_pending_htlc_forwards();
3197 check_added_monitors!(nodes[1], 1);
3199 let events = nodes[1].node.get_and_clear_pending_msg_events();
3200 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3201 match events[if deliver_bs_raa { 1 } else { 0 }] {
3202 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3203 _ => panic!("Unexpected event"),
3205 match events[if deliver_bs_raa { 2 } else { 1 }] {
3206 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3207 assert_eq!(channel_id, chan_2.2);
3208 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3210 _ => panic!("Unexpected event"),
3214 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3215 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3216 assert_eq!(update_add_htlcs.len(), 1);
3217 assert!(update_fulfill_htlcs.is_empty());
3218 assert!(update_fail_htlcs.is_empty());
3219 assert!(update_fail_malformed_htlcs.is_empty());
3221 _ => panic!("Unexpected event"),
3224 match events[if deliver_bs_raa { 3 } else { 2 }] {
3225 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3226 assert!(update_add_htlcs.is_empty());
3227 assert_eq!(update_fail_htlcs.len(), 3);
3228 assert!(update_fulfill_htlcs.is_empty());
3229 assert!(update_fail_malformed_htlcs.is_empty());
3230 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3232 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3233 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3234 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3236 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3238 let events = nodes[0].node.get_and_clear_pending_events();
3239 assert_eq!(events.len(), 3);
3241 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3242 assert!(failed_htlcs.insert(payment_hash.0));
3243 // If we delivered B's RAA we got an unknown preimage error, not something
3244 // that we should update our routing table for.
3245 if !deliver_bs_raa {
3246 assert!(network_update.is_some());
3249 _ => panic!("Unexpected event"),
3252 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3253 assert!(failed_htlcs.insert(payment_hash.0));
3254 assert!(network_update.is_some());
3256 _ => panic!("Unexpected event"),
3259 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3260 assert!(failed_htlcs.insert(payment_hash.0));
3261 assert!(network_update.is_some());
3263 _ => panic!("Unexpected event"),
3266 _ => panic!("Unexpected event"),
3269 assert!(failed_htlcs.contains(&first_payment_hash.0));
3270 assert!(failed_htlcs.contains(&second_payment_hash.0));
3271 assert!(failed_htlcs.contains(&third_payment_hash.0));
3275 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3276 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3277 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3278 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3279 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3283 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3284 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3285 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3286 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3287 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3291 fn fail_backward_pending_htlc_upon_channel_failure() {
3292 let chanmon_cfgs = create_chanmon_cfgs(2);
3293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3295 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3296 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3298 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3300 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3301 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3302 check_added_monitors!(nodes[0], 1);
3304 let payment_event = {
3305 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3306 assert_eq!(events.len(), 1);
3307 SendEvent::from_event(events.remove(0))
3309 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3310 assert_eq!(payment_event.msgs.len(), 1);
3313 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3314 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3316 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3317 check_added_monitors!(nodes[0], 0);
3319 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3322 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3324 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3326 let secp_ctx = Secp256k1::new();
3327 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3328 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3329 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3330 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3331 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3333 // Send a 0-msat update_add_htlc to fail the channel.
3334 let update_add_htlc = msgs::UpdateAddHTLC {
3340 onion_routing_packet,
3342 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3344 let events = nodes[0].node.get_and_clear_pending_events();
3345 assert_eq!(events.len(), 2);
3346 // Check that Alice fails backward the pending HTLC from the second payment.
3348 Event::PaymentPathFailed { payment_hash, .. } => {
3349 assert_eq!(payment_hash, failed_payment_hash);
3351 _ => panic!("Unexpected event"),
3354 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3355 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3357 _ => panic!("Unexpected event {:?}", events[1]),
3359 check_closed_broadcast!(nodes[0], true);
3360 check_added_monitors!(nodes[0], 1);
3364 fn test_htlc_ignore_latest_remote_commitment() {
3365 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3366 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3367 let chanmon_cfgs = create_chanmon_cfgs(2);
3368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3370 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3371 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3373 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3374 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3375 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3376 check_closed_broadcast!(nodes[0], true);
3377 check_added_monitors!(nodes[0], 1);
3378 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3380 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3381 assert_eq!(node_txn.len(), 3);
3382 assert_eq!(node_txn[0], node_txn[1]);
3384 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3385 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3386 check_closed_broadcast!(nodes[1], true);
3387 check_added_monitors!(nodes[1], 1);
3388 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3390 // Duplicate the connect_block call since this may happen due to other listeners
3391 // registering new transactions
3392 header.prev_blockhash = header.block_hash();
3393 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3397 fn test_force_close_fail_back() {
3398 // Check which HTLCs are failed-backwards on channel force-closure
3399 let chanmon_cfgs = create_chanmon_cfgs(3);
3400 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3401 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3402 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3403 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3404 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3406 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3408 let mut payment_event = {
3409 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3410 check_added_monitors!(nodes[0], 1);
3412 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3413 assert_eq!(events.len(), 1);
3414 SendEvent::from_event(events.remove(0))
3417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3418 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3420 expect_pending_htlcs_forwardable!(nodes[1]);
3422 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3423 assert_eq!(events_2.len(), 1);
3424 payment_event = SendEvent::from_event(events_2.remove(0));
3425 assert_eq!(payment_event.msgs.len(), 1);
3427 check_added_monitors!(nodes[1], 1);
3428 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3429 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3430 check_added_monitors!(nodes[2], 1);
3431 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3433 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3434 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3435 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3437 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3438 check_closed_broadcast!(nodes[2], true);
3439 check_added_monitors!(nodes[2], 1);
3440 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3442 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3443 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3444 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3445 // back to nodes[1] upon timeout otherwise.
3446 assert_eq!(node_txn.len(), 1);
3450 mine_transaction(&nodes[1], &tx);
3452 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3453 check_closed_broadcast!(nodes[1], true);
3454 check_added_monitors!(nodes[1], 1);
3455 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3457 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3459 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3460 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3462 mine_transaction(&nodes[2], &tx);
3463 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3464 assert_eq!(node_txn.len(), 1);
3465 assert_eq!(node_txn[0].input.len(), 1);
3466 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3467 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3468 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3470 check_spends!(node_txn[0], tx);
3474 fn test_dup_events_on_peer_disconnect() {
3475 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3476 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3477 // as we used to generate the event immediately upon receipt of the payment preimage in the
3478 // update_fulfill_htlc message.
3480 let chanmon_cfgs = create_chanmon_cfgs(2);
3481 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3482 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3483 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3484 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3486 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3488 nodes[1].node.claim_funds(payment_preimage);
3489 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3490 check_added_monitors!(nodes[1], 1);
3491 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3492 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3493 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3495 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3496 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3498 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3499 expect_payment_path_successful!(nodes[0]);
3503 fn test_peer_disconnected_before_funding_broadcasted() {
3504 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3505 // before the funding transaction has been broadcasted.
3506 let chanmon_cfgs = create_chanmon_cfgs(2);
3507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3509 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3511 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3512 // broadcasted, even though it's created by `nodes[0]`.
3513 let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3514 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3515 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3516 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3517 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3519 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3520 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3522 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3524 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3525 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3527 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3528 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3531 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3534 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3535 // disconnected before the funding transaction was broadcasted.
3536 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3537 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3539 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3540 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3544 fn test_simple_peer_disconnect() {
3545 // Test that we can reconnect when there are no lost messages
3546 let chanmon_cfgs = create_chanmon_cfgs(3);
3547 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3548 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3549 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3550 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3551 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3553 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3554 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3555 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3557 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3558 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3559 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3560 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3562 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3563 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3564 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3566 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3567 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3568 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3569 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3571 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3574 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3575 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3577 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3579 let events = nodes[0].node.get_and_clear_pending_events();
3580 assert_eq!(events.len(), 3);
3582 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3583 assert_eq!(payment_preimage, payment_preimage_3);
3584 assert_eq!(payment_hash, payment_hash_3);
3586 _ => panic!("Unexpected event"),
3589 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3590 assert_eq!(payment_hash, payment_hash_5);
3591 assert!(rejected_by_dest);
3593 _ => panic!("Unexpected event"),
3596 Event::PaymentPathSuccessful { .. } => {},
3597 _ => panic!("Unexpected event"),
3601 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3602 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3605 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3606 // Test that we can reconnect when in-flight HTLC updates get dropped
3607 let chanmon_cfgs = create_chanmon_cfgs(2);
3608 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3609 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3610 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3612 let mut as_funding_locked = None;
3613 if messages_delivered == 0 {
3614 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3615 as_funding_locked = Some(funding_locked);
3616 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3617 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3618 // it before the channel_reestablish message.
3620 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3623 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3625 let payment_event = {
3626 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3627 check_added_monitors!(nodes[0], 1);
3629 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3630 assert_eq!(events.len(), 1);
3631 SendEvent::from_event(events.remove(0))
3633 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3635 if messages_delivered < 2 {
3636 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3638 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3639 if messages_delivered >= 3 {
3640 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3641 check_added_monitors!(nodes[1], 1);
3642 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3644 if messages_delivered >= 4 {
3645 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3646 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3647 check_added_monitors!(nodes[0], 1);
3649 if messages_delivered >= 5 {
3650 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3651 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3652 // No commitment_signed so get_event_msg's assert(len == 1) passes
3653 check_added_monitors!(nodes[0], 1);
3655 if messages_delivered >= 6 {
3656 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3657 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3658 check_added_monitors!(nodes[1], 1);
3665 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3666 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3667 if messages_delivered < 3 {
3668 if simulate_broken_lnd {
3669 // lnd has a long-standing bug where they send a funding_locked prior to a
3670 // channel_reestablish if you reconnect prior to funding_locked time.
3672 // Here we simulate that behavior, delivering a funding_locked immediately on
3673 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3674 // in `reconnect_nodes` but we currently don't fail based on that.
3676 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3677 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3679 // Even if the funding_locked messages get exchanged, as long as nothing further was
3680 // received on either side, both sides will need to resend them.
3681 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3682 } else if messages_delivered == 3 {
3683 // nodes[0] still wants its RAA + commitment_signed
3684 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3685 } else if messages_delivered == 4 {
3686 // nodes[0] still wants its commitment_signed
3687 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3688 } else if messages_delivered == 5 {
3689 // nodes[1] still wants its final RAA
3690 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3691 } else if messages_delivered == 6 {
3692 // Everything was delivered...
3693 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3696 let events_1 = nodes[1].node.get_and_clear_pending_events();
3697 assert_eq!(events_1.len(), 1);
3699 Event::PendingHTLCsForwardable { .. } => { },
3700 _ => panic!("Unexpected event"),
3703 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3704 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3705 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3707 nodes[1].node.process_pending_htlc_forwards();
3709 let events_2 = nodes[1].node.get_and_clear_pending_events();
3710 assert_eq!(events_2.len(), 1);
3712 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3713 assert_eq!(payment_hash_1, *payment_hash);
3714 assert_eq!(amt, 1000000);
3716 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3717 assert!(payment_preimage.is_none());
3718 assert_eq!(payment_secret_1, *payment_secret);
3720 _ => panic!("expected PaymentPurpose::InvoicePayment")
3723 _ => panic!("Unexpected event"),
3726 nodes[1].node.claim_funds(payment_preimage_1);
3727 check_added_monitors!(nodes[1], 1);
3728 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3730 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3731 assert_eq!(events_3.len(), 1);
3732 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3733 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3734 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3735 assert!(updates.update_add_htlcs.is_empty());
3736 assert!(updates.update_fail_htlcs.is_empty());
3737 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3738 assert!(updates.update_fail_malformed_htlcs.is_empty());
3739 assert!(updates.update_fee.is_none());
3740 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3742 _ => panic!("Unexpected event"),
3745 if messages_delivered >= 1 {
3746 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3748 let events_4 = nodes[0].node.get_and_clear_pending_events();
3749 assert_eq!(events_4.len(), 1);
3751 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3752 assert_eq!(payment_preimage_1, *payment_preimage);
3753 assert_eq!(payment_hash_1, *payment_hash);
3755 _ => panic!("Unexpected event"),
3758 if messages_delivered >= 2 {
3759 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3760 check_added_monitors!(nodes[0], 1);
3761 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3763 if messages_delivered >= 3 {
3764 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3765 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3766 check_added_monitors!(nodes[1], 1);
3768 if messages_delivered >= 4 {
3769 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3770 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3771 // No commitment_signed so get_event_msg's assert(len == 1) passes
3772 check_added_monitors!(nodes[1], 1);
3774 if messages_delivered >= 5 {
3775 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3776 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3777 check_added_monitors!(nodes[0], 1);
3784 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3785 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3786 if messages_delivered < 2 {
3787 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3788 if messages_delivered < 1 {
3789 expect_payment_sent!(nodes[0], payment_preimage_1);
3791 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3793 } else if messages_delivered == 2 {
3794 // nodes[0] still wants its RAA + commitment_signed
3795 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3796 } else if messages_delivered == 3 {
3797 // nodes[0] still wants its commitment_signed
3798 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3799 } else if messages_delivered == 4 {
3800 // nodes[1] still wants its final RAA
3801 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3802 } else if messages_delivered == 5 {
3803 // Everything was delivered...
3804 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3807 if messages_delivered == 1 || messages_delivered == 2 {
3808 expect_payment_path_successful!(nodes[0]);
3811 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3812 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3815 if messages_delivered > 2 {
3816 expect_payment_path_successful!(nodes[0]);
3819 // Channel should still work fine...
3820 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3821 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3822 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3826 fn test_drop_messages_peer_disconnect_a() {
3827 do_test_drop_messages_peer_disconnect(0, true);
3828 do_test_drop_messages_peer_disconnect(0, false);
3829 do_test_drop_messages_peer_disconnect(1, false);
3830 do_test_drop_messages_peer_disconnect(2, false);
3834 fn test_drop_messages_peer_disconnect_b() {
3835 do_test_drop_messages_peer_disconnect(3, false);
3836 do_test_drop_messages_peer_disconnect(4, false);
3837 do_test_drop_messages_peer_disconnect(5, false);
3838 do_test_drop_messages_peer_disconnect(6, false);
3842 fn test_funding_peer_disconnect() {
3843 // Test that we can lock in our funding tx while disconnected
3844 let chanmon_cfgs = create_chanmon_cfgs(2);
3845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3847 let persister: test_utils::TestPersister;
3848 let new_chain_monitor: test_utils::TestChainMonitor;
3849 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3850 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3851 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3853 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3854 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3856 confirm_transaction(&nodes[0], &tx);
3857 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3858 assert!(events_1.is_empty());
3860 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3862 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3863 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3865 confirm_transaction(&nodes[1], &tx);
3866 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3867 assert!(events_2.is_empty());
3869 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3870 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3871 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3872 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3874 // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3875 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3876 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3877 assert_eq!(events_3.len(), 1);
3878 let as_funding_locked = match events_3[0] {
3879 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3880 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3883 _ => panic!("Unexpected event {:?}", events_3[0]),
3886 // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3887 // announcement_signatures as well as channel_update.
3888 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3889 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3890 assert_eq!(events_4.len(), 3);
3892 let bs_funding_locked = match events_4[0] {
3893 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3894 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3895 chan_id = msg.channel_id;
3898 _ => panic!("Unexpected event {:?}", events_4[0]),
3900 let bs_announcement_sigs = match events_4[1] {
3901 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3902 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3905 _ => panic!("Unexpected event {:?}", events_4[1]),
3908 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3909 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3911 _ => panic!("Unexpected event {:?}", events_4[2]),
3914 // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3915 // generates a duplicative private channel_update
3916 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3917 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3918 assert_eq!(events_5.len(), 1);
3920 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3921 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3923 _ => panic!("Unexpected event {:?}", events_5[0]),
3926 // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3927 // announcement_signatures.
3928 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3929 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3930 assert_eq!(events_6.len(), 1);
3931 let as_announcement_sigs = match events_6[0] {
3932 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3933 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3936 _ => panic!("Unexpected event {:?}", events_6[0]),
3939 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3940 // broadcast the channel announcement globally, as well as re-send its (now-public)
3942 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3943 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3944 assert_eq!(events_7.len(), 1);
3945 let (chan_announcement, as_update) = match events_7[0] {
3946 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3947 (msg.clone(), update_msg.clone())
3949 _ => panic!("Unexpected event {:?}", events_7[0]),
3952 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3953 // same channel_announcement.
3954 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3955 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3956 assert_eq!(events_8.len(), 1);
3957 let bs_update = match events_8[0] {
3958 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3959 assert_eq!(*msg, chan_announcement);
3962 _ => panic!("Unexpected event {:?}", events_8[0]),
3965 // Provide the channel announcement and public updates to the network graph
3966 nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3967 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3968 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3970 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3971 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3972 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3974 // Check that after deserialization and reconnection we can still generate an identical
3975 // channel_announcement from the cached signatures.
3976 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3978 let nodes_0_serialized = nodes[0].node.encode();
3979 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3980 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3982 persister = test_utils::TestPersister::new();
3983 let keys_manager = &chanmon_cfgs[0].keys_manager;
3984 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);
3985 nodes[0].chain_monitor = &new_chain_monitor;
3986 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3987 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3988 &mut chan_0_monitor_read, keys_manager).unwrap();
3989 assert!(chan_0_monitor_read.is_empty());
3991 let mut nodes_0_read = &nodes_0_serialized[..];
3992 let (_, nodes_0_deserialized_tmp) = {
3993 let mut channel_monitors = HashMap::new();
3994 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3995 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3996 default_config: UserConfig::default(),
3998 fee_estimator: node_cfgs[0].fee_estimator,
3999 chain_monitor: nodes[0].chain_monitor,
4000 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4001 logger: nodes[0].logger,
4005 nodes_0_deserialized = nodes_0_deserialized_tmp;
4006 assert!(nodes_0_read.is_empty());
4008 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
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));
4014 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4015 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4016 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4017 let mut found_announcement = false;
4018 for event in msgs.iter() {
4020 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4021 if *msg == chan_announcement { found_announcement = true; }
4023 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4024 _ => panic!("Unexpected event"),
4027 assert!(found_announcement);
4031 fn test_funding_locked_without_best_block_updated() {
4032 // Previously, if we were offline when a funding transaction was locked in, and then we came
4033 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4034 // generate a funding_locked until a later best_block_updated. This tests that we generate the
4035 // funding_locked immediately instead.
4036 let chanmon_cfgs = create_chanmon_cfgs(2);
4037 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4038 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4039 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4040 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4042 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4044 let conf_height = nodes[0].best_block_info().1 + 1;
4045 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4046 let block_txn = [funding_tx];
4047 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4048 let conf_block_header = nodes[0].get_block_header(conf_height);
4049 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4051 // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
4052 let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
4053 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
4057 fn test_drop_messages_peer_disconnect_dual_htlc() {
4058 // Test that we can handle reconnecting when both sides of a channel have pending
4059 // commitment_updates when we disconnect.
4060 let chanmon_cfgs = create_chanmon_cfgs(2);
4061 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4062 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4063 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4064 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4066 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4068 // Now try to send a second payment which will fail to send
4069 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4070 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4071 check_added_monitors!(nodes[0], 1);
4073 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4074 assert_eq!(events_1.len(), 1);
4076 MessageSendEvent::UpdateHTLCs { .. } => {},
4077 _ => panic!("Unexpected event"),
4080 nodes[1].node.claim_funds(payment_preimage_1);
4081 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4082 check_added_monitors!(nodes[1], 1);
4084 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4085 assert_eq!(events_2.len(), 1);
4087 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
4088 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4089 assert!(update_add_htlcs.is_empty());
4090 assert_eq!(update_fulfill_htlcs.len(), 1);
4091 assert!(update_fail_htlcs.is_empty());
4092 assert!(update_fail_malformed_htlcs.is_empty());
4093 assert!(update_fee.is_none());
4095 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4096 let events_3 = nodes[0].node.get_and_clear_pending_events();
4097 assert_eq!(events_3.len(), 1);
4099 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4100 assert_eq!(*payment_preimage, payment_preimage_1);
4101 assert_eq!(*payment_hash, payment_hash_1);
4103 _ => panic!("Unexpected event"),
4106 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4107 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4108 // No commitment_signed so get_event_msg's assert(len == 1) passes
4109 check_added_monitors!(nodes[0], 1);
4111 _ => panic!("Unexpected event"),
4114 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4115 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4117 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4118 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4119 assert_eq!(reestablish_1.len(), 1);
4120 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4121 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4122 assert_eq!(reestablish_2.len(), 1);
4124 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4125 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4126 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4127 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4129 assert!(as_resp.0.is_none());
4130 assert!(bs_resp.0.is_none());
4132 assert!(bs_resp.1.is_none());
4133 assert!(bs_resp.2.is_none());
4135 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4137 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4138 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4139 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4140 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4141 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4142 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4143 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4144 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4145 // No commitment_signed so get_event_msg's assert(len == 1) passes
4146 check_added_monitors!(nodes[1], 1);
4148 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4149 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4150 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4151 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4152 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4153 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4154 assert!(bs_second_commitment_signed.update_fee.is_none());
4155 check_added_monitors!(nodes[1], 1);
4157 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4158 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4159 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4160 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4161 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4162 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4163 assert!(as_commitment_signed.update_fee.is_none());
4164 check_added_monitors!(nodes[0], 1);
4166 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4167 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4168 // No commitment_signed so get_event_msg's assert(len == 1) passes
4169 check_added_monitors!(nodes[0], 1);
4171 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4172 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4173 // No commitment_signed so get_event_msg's assert(len == 1) passes
4174 check_added_monitors!(nodes[1], 1);
4176 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4177 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4178 check_added_monitors!(nodes[1], 1);
4180 expect_pending_htlcs_forwardable!(nodes[1]);
4182 let events_5 = nodes[1].node.get_and_clear_pending_events();
4183 assert_eq!(events_5.len(), 1);
4185 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4186 assert_eq!(payment_hash_2, *payment_hash);
4188 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4189 assert!(payment_preimage.is_none());
4190 assert_eq!(payment_secret_2, *payment_secret);
4192 _ => panic!("expected PaymentPurpose::InvoicePayment")
4195 _ => panic!("Unexpected event"),
4198 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4199 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4200 check_added_monitors!(nodes[0], 1);
4202 expect_payment_path_successful!(nodes[0]);
4203 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4206 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4207 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4208 // to avoid our counterparty failing the channel.
4209 let chanmon_cfgs = create_chanmon_cfgs(2);
4210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4212 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4214 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4216 let our_payment_hash = if send_partial_mpp {
4217 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4218 // Use the utility function send_payment_along_path to send the payment with MPP data which
4219 // indicates there are more HTLCs coming.
4220 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4221 let payment_id = PaymentId([42; 32]);
4222 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
4223 check_added_monitors!(nodes[0], 1);
4224 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4225 assert_eq!(events.len(), 1);
4226 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4227 // hop should *not* yet generate any PaymentReceived event(s).
4228 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4231 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4234 let mut block = Block {
4235 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4238 connect_block(&nodes[0], &block);
4239 connect_block(&nodes[1], &block);
4240 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4241 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4242 block.header.prev_blockhash = block.block_hash();
4243 connect_block(&nodes[0], &block);
4244 connect_block(&nodes[1], &block);
4247 expect_pending_htlcs_forwardable!(nodes[1]);
4249 check_added_monitors!(nodes[1], 1);
4250 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4251 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4252 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4253 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4254 assert!(htlc_timeout_updates.update_fee.is_none());
4256 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4257 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4258 // 100_000 msat as u64, followed by the height at which we failed back above
4259 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4260 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4261 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4265 fn test_htlc_timeout() {
4266 do_test_htlc_timeout(true);
4267 do_test_htlc_timeout(false);
4270 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4271 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4272 let chanmon_cfgs = create_chanmon_cfgs(3);
4273 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4274 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4275 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4276 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4277 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4279 // Make sure all nodes are at the same starting height
4280 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4281 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4282 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4284 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4285 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4287 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4289 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4290 check_added_monitors!(nodes[1], 1);
4292 // Now attempt to route a second payment, which should be placed in the holding cell
4293 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4294 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4295 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4297 check_added_monitors!(nodes[0], 1);
4298 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4299 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4300 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4301 expect_pending_htlcs_forwardable!(nodes[1]);
4303 check_added_monitors!(nodes[1], 0);
4305 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4306 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4307 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4308 connect_blocks(&nodes[1], 1);
4311 expect_pending_htlcs_forwardable!(nodes[1]);
4312 check_added_monitors!(nodes[1], 1);
4313 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4314 assert_eq!(fail_commit.len(), 1);
4315 match fail_commit[0] {
4316 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4317 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4318 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4320 _ => unreachable!(),
4322 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4324 let events = nodes[1].node.get_and_clear_pending_events();
4325 assert_eq!(events.len(), 2);
4326 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4327 assert_eq!(*payment_hash, second_payment_hash);
4328 } else { panic!("Unexpected event"); }
4329 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4330 assert_eq!(*payment_hash, second_payment_hash);
4331 } else { panic!("Unexpected event"); }
4336 fn test_holding_cell_htlc_add_timeouts() {
4337 do_test_holding_cell_htlc_add_timeouts(false);
4338 do_test_holding_cell_htlc_add_timeouts(true);
4342 fn test_no_txn_manager_serialize_deserialize() {
4343 let chanmon_cfgs = create_chanmon_cfgs(2);
4344 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4345 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4346 let logger: test_utils::TestLogger;
4347 let fee_estimator: test_utils::TestFeeEstimator;
4348 let persister: test_utils::TestPersister;
4349 let new_chain_monitor: test_utils::TestChainMonitor;
4350 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4351 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4353 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4355 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4357 let nodes_0_serialized = nodes[0].node.encode();
4358 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4359 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4360 .write(&mut chan_0_monitor_serialized).unwrap();
4362 logger = test_utils::TestLogger::new();
4363 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4364 persister = test_utils::TestPersister::new();
4365 let keys_manager = &chanmon_cfgs[0].keys_manager;
4366 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4367 nodes[0].chain_monitor = &new_chain_monitor;
4368 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4369 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4370 &mut chan_0_monitor_read, keys_manager).unwrap();
4371 assert!(chan_0_monitor_read.is_empty());
4373 let mut nodes_0_read = &nodes_0_serialized[..];
4374 let config = UserConfig::default();
4375 let (_, nodes_0_deserialized_tmp) = {
4376 let mut channel_monitors = HashMap::new();
4377 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4378 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4379 default_config: config,
4381 fee_estimator: &fee_estimator,
4382 chain_monitor: nodes[0].chain_monitor,
4383 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4388 nodes_0_deserialized = nodes_0_deserialized_tmp;
4389 assert!(nodes_0_read.is_empty());
4391 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4392 nodes[0].node = &nodes_0_deserialized;
4393 assert_eq!(nodes[0].node.list_channels().len(), 1);
4394 check_added_monitors!(nodes[0], 1);
4396 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4397 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4398 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4399 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4401 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4402 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4403 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4404 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4406 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4407 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4408 for node in nodes.iter() {
4409 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4410 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4411 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4414 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4418 fn test_manager_serialize_deserialize_events() {
4419 // This test makes sure the events field in ChannelManager survives de/serialization
4420 let chanmon_cfgs = create_chanmon_cfgs(2);
4421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4422 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4423 let fee_estimator: test_utils::TestFeeEstimator;
4424 let persister: test_utils::TestPersister;
4425 let logger: test_utils::TestLogger;
4426 let new_chain_monitor: test_utils::TestChainMonitor;
4427 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4428 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4430 // Start creating a channel, but stop right before broadcasting the funding transaction
4431 let channel_value = 100000;
4432 let push_msat = 10001;
4433 let a_flags = InitFeatures::known();
4434 let b_flags = InitFeatures::known();
4435 let node_a = nodes.remove(0);
4436 let node_b = nodes.remove(0);
4437 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4438 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()));
4439 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()));
4441 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4443 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4444 check_added_monitors!(node_a, 0);
4446 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()));
4448 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4449 assert_eq!(added_monitors.len(), 1);
4450 assert_eq!(added_monitors[0].0, funding_output);
4451 added_monitors.clear();
4454 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4455 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4457 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4458 assert_eq!(added_monitors.len(), 1);
4459 assert_eq!(added_monitors[0].0, funding_output);
4460 added_monitors.clear();
4462 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4467 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4468 let nodes_0_serialized = nodes[0].node.encode();
4469 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4470 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4472 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4473 logger = test_utils::TestLogger::new();
4474 persister = test_utils::TestPersister::new();
4475 let keys_manager = &chanmon_cfgs[0].keys_manager;
4476 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4477 nodes[0].chain_monitor = &new_chain_monitor;
4478 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4479 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4480 &mut chan_0_monitor_read, keys_manager).unwrap();
4481 assert!(chan_0_monitor_read.is_empty());
4483 let mut nodes_0_read = &nodes_0_serialized[..];
4484 let config = UserConfig::default();
4485 let (_, nodes_0_deserialized_tmp) = {
4486 let mut channel_monitors = HashMap::new();
4487 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4488 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4489 default_config: config,
4491 fee_estimator: &fee_estimator,
4492 chain_monitor: nodes[0].chain_monitor,
4493 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4498 nodes_0_deserialized = nodes_0_deserialized_tmp;
4499 assert!(nodes_0_read.is_empty());
4501 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4503 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4504 nodes[0].node = &nodes_0_deserialized;
4506 // After deserializing, make sure the funding_transaction is still held by the channel manager
4507 let events_4 = nodes[0].node.get_and_clear_pending_events();
4508 assert_eq!(events_4.len(), 0);
4509 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4510 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4512 // Make sure the channel is functioning as though the de/serialization never happened
4513 assert_eq!(nodes[0].node.list_channels().len(), 1);
4514 check_added_monitors!(nodes[0], 1);
4516 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4517 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4518 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4519 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4521 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4522 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4523 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4524 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4526 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4527 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4528 for node in nodes.iter() {
4529 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4530 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4531 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4534 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4538 fn test_simple_manager_serialize_deserialize() {
4539 let chanmon_cfgs = create_chanmon_cfgs(2);
4540 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4541 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4542 let logger: test_utils::TestLogger;
4543 let fee_estimator: test_utils::TestFeeEstimator;
4544 let persister: test_utils::TestPersister;
4545 let new_chain_monitor: test_utils::TestChainMonitor;
4546 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4547 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4548 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4550 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4551 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4553 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4555 let nodes_0_serialized = nodes[0].node.encode();
4556 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4557 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4559 logger = test_utils::TestLogger::new();
4560 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4561 persister = test_utils::TestPersister::new();
4562 let keys_manager = &chanmon_cfgs[0].keys_manager;
4563 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4564 nodes[0].chain_monitor = &new_chain_monitor;
4565 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4566 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4567 &mut chan_0_monitor_read, keys_manager).unwrap();
4568 assert!(chan_0_monitor_read.is_empty());
4570 let mut nodes_0_read = &nodes_0_serialized[..];
4571 let (_, nodes_0_deserialized_tmp) = {
4572 let mut channel_monitors = HashMap::new();
4573 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4574 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4575 default_config: UserConfig::default(),
4577 fee_estimator: &fee_estimator,
4578 chain_monitor: nodes[0].chain_monitor,
4579 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4584 nodes_0_deserialized = nodes_0_deserialized_tmp;
4585 assert!(nodes_0_read.is_empty());
4587 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4588 nodes[0].node = &nodes_0_deserialized;
4589 check_added_monitors!(nodes[0], 1);
4591 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4593 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4594 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4598 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4599 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4600 let chanmon_cfgs = create_chanmon_cfgs(4);
4601 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4602 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4603 let logger: test_utils::TestLogger;
4604 let fee_estimator: test_utils::TestFeeEstimator;
4605 let persister: test_utils::TestPersister;
4606 let new_chain_monitor: test_utils::TestChainMonitor;
4607 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4608 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4609 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4610 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4611 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4613 let mut node_0_stale_monitors_serialized = Vec::new();
4614 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4615 let mut writer = test_utils::TestVecWriter(Vec::new());
4616 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4617 node_0_stale_monitors_serialized.push(writer.0);
4620 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4622 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4623 let nodes_0_serialized = nodes[0].node.encode();
4625 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4626 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4627 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4628 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4630 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4632 let mut node_0_monitors_serialized = Vec::new();
4633 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4634 let mut writer = test_utils::TestVecWriter(Vec::new());
4635 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4636 node_0_monitors_serialized.push(writer.0);
4639 logger = test_utils::TestLogger::new();
4640 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4641 persister = test_utils::TestPersister::new();
4642 let keys_manager = &chanmon_cfgs[0].keys_manager;
4643 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4644 nodes[0].chain_monitor = &new_chain_monitor;
4647 let mut node_0_stale_monitors = Vec::new();
4648 for serialized in node_0_stale_monitors_serialized.iter() {
4649 let mut read = &serialized[..];
4650 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4651 assert!(read.is_empty());
4652 node_0_stale_monitors.push(monitor);
4655 let mut node_0_monitors = Vec::new();
4656 for serialized in node_0_monitors_serialized.iter() {
4657 let mut read = &serialized[..];
4658 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4659 assert!(read.is_empty());
4660 node_0_monitors.push(monitor);
4663 let mut nodes_0_read = &nodes_0_serialized[..];
4664 if let Err(msgs::DecodeError::InvalidValue) =
4665 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4666 default_config: UserConfig::default(),
4668 fee_estimator: &fee_estimator,
4669 chain_monitor: nodes[0].chain_monitor,
4670 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4672 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4674 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4677 let mut nodes_0_read = &nodes_0_serialized[..];
4678 let (_, nodes_0_deserialized_tmp) =
4679 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4680 default_config: UserConfig::default(),
4682 fee_estimator: &fee_estimator,
4683 chain_monitor: nodes[0].chain_monitor,
4684 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4686 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4688 nodes_0_deserialized = nodes_0_deserialized_tmp;
4689 assert!(nodes_0_read.is_empty());
4691 { // Channel close should result in a commitment tx
4692 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4693 assert_eq!(txn.len(), 1);
4694 check_spends!(txn[0], funding_tx);
4695 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4698 for monitor in node_0_monitors.drain(..) {
4699 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4700 check_added_monitors!(nodes[0], 1);
4702 nodes[0].node = &nodes_0_deserialized;
4703 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4705 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4706 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4707 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4708 //... and we can even still claim the payment!
4709 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4711 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4712 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4713 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4714 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4715 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4716 assert_eq!(msg_events.len(), 1);
4717 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4719 &ErrorAction::SendErrorMessage { ref msg } => {
4720 assert_eq!(msg.channel_id, channel_id);
4722 _ => panic!("Unexpected event!"),
4727 macro_rules! check_spendable_outputs {
4728 ($node: expr, $keysinterface: expr) => {
4730 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4731 let mut txn = Vec::new();
4732 let mut all_outputs = Vec::new();
4733 let secp_ctx = Secp256k1::new();
4734 for event in events.drain(..) {
4736 Event::SpendableOutputs { mut outputs } => {
4737 for outp in outputs.drain(..) {
4738 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4739 all_outputs.push(outp);
4742 _ => panic!("Unexpected event"),
4745 if all_outputs.len() > 1 {
4746 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) {
4756 fn test_claim_sizeable_push_msat() {
4757 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4758 let chanmon_cfgs = create_chanmon_cfgs(2);
4759 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4760 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4761 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4763 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4764 nodes[1].node.force_close_channel(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4765 check_closed_broadcast!(nodes[1], true);
4766 check_added_monitors!(nodes[1], 1);
4767 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4768 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4769 assert_eq!(node_txn.len(), 1);
4770 check_spends!(node_txn[0], chan.3);
4771 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
4773 mine_transaction(&nodes[1], &node_txn[0]);
4774 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4776 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4777 assert_eq!(spend_txn.len(), 1);
4778 assert_eq!(spend_txn[0].input.len(), 1);
4779 check_spends!(spend_txn[0], node_txn[0]);
4780 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4784 fn test_claim_on_remote_sizeable_push_msat() {
4785 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4786 // to_remote output is encumbered by a P2WPKH
4787 let chanmon_cfgs = create_chanmon_cfgs(2);
4788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4790 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4792 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4793 nodes[0].node.force_close_channel(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4794 check_closed_broadcast!(nodes[0], true);
4795 check_added_monitors!(nodes[0], 1);
4796 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4798 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4799 assert_eq!(node_txn.len(), 1);
4800 check_spends!(node_txn[0], chan.3);
4801 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
4803 mine_transaction(&nodes[1], &node_txn[0]);
4804 check_closed_broadcast!(nodes[1], true);
4805 check_added_monitors!(nodes[1], 1);
4806 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4807 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4809 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4810 assert_eq!(spend_txn.len(), 1);
4811 check_spends!(spend_txn[0], node_txn[0]);
4815 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4816 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4817 // to_remote output is encumbered by a P2WPKH
4819 let chanmon_cfgs = create_chanmon_cfgs(2);
4820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4822 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4824 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4825 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4826 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4827 assert_eq!(revoked_local_txn[0].input.len(), 1);
4828 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4830 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4831 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4832 check_closed_broadcast!(nodes[1], true);
4833 check_added_monitors!(nodes[1], 1);
4834 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4836 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4837 mine_transaction(&nodes[1], &node_txn[0]);
4838 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4840 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4841 assert_eq!(spend_txn.len(), 3);
4842 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4843 check_spends!(spend_txn[1], node_txn[0]);
4844 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4848 fn test_static_spendable_outputs_preimage_tx() {
4849 let chanmon_cfgs = create_chanmon_cfgs(2);
4850 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4851 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4852 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4854 // Create some initial channels
4855 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4857 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4859 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4860 assert_eq!(commitment_tx[0].input.len(), 1);
4861 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4863 // Settle A's commitment tx on B's chain
4864 nodes[1].node.claim_funds(payment_preimage);
4865 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4866 check_added_monitors!(nodes[1], 1);
4867 mine_transaction(&nodes[1], &commitment_tx[0]);
4868 check_added_monitors!(nodes[1], 1);
4869 let events = nodes[1].node.get_and_clear_pending_msg_events();
4871 MessageSendEvent::UpdateHTLCs { .. } => {},
4872 _ => panic!("Unexpected event"),
4875 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4876 _ => panic!("Unexepected event"),
4879 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4880 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4881 assert_eq!(node_txn.len(), 3);
4882 check_spends!(node_txn[0], commitment_tx[0]);
4883 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4884 check_spends!(node_txn[1], chan_1.3);
4885 check_spends!(node_txn[2], node_txn[1]);
4887 mine_transaction(&nodes[1], &node_txn[0]);
4888 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4889 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4891 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4892 assert_eq!(spend_txn.len(), 1);
4893 check_spends!(spend_txn[0], node_txn[0]);
4897 fn test_static_spendable_outputs_timeout_tx() {
4898 let chanmon_cfgs = create_chanmon_cfgs(2);
4899 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4900 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4901 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4903 // Create some initial channels
4904 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4906 // Rebalance the network a bit by relaying one payment through all the channels ...
4907 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4909 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4911 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4912 assert_eq!(commitment_tx[0].input.len(), 1);
4913 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4915 // Settle A's commitment tx on B' chain
4916 mine_transaction(&nodes[1], &commitment_tx[0]);
4917 check_added_monitors!(nodes[1], 1);
4918 let events = nodes[1].node.get_and_clear_pending_msg_events();
4920 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4921 _ => panic!("Unexpected event"),
4923 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4925 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4926 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4927 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4928 check_spends!(node_txn[0], chan_1.3.clone());
4929 check_spends!(node_txn[1], commitment_tx[0].clone());
4930 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4932 mine_transaction(&nodes[1], &node_txn[1]);
4933 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4934 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4935 expect_payment_failed!(nodes[1], our_payment_hash, true);
4937 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4938 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4939 check_spends!(spend_txn[0], commitment_tx[0]);
4940 check_spends!(spend_txn[1], node_txn[1]);
4941 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4945 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4946 let chanmon_cfgs = create_chanmon_cfgs(2);
4947 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4948 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4949 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4951 // Create some initial channels
4952 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4954 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4955 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4956 assert_eq!(revoked_local_txn[0].input.len(), 1);
4957 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4959 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4961 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4962 check_closed_broadcast!(nodes[1], true);
4963 check_added_monitors!(nodes[1], 1);
4964 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4966 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4967 assert_eq!(node_txn.len(), 2);
4968 assert_eq!(node_txn[0].input.len(), 2);
4969 check_spends!(node_txn[0], revoked_local_txn[0]);
4971 mine_transaction(&nodes[1], &node_txn[0]);
4972 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4974 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4975 assert_eq!(spend_txn.len(), 1);
4976 check_spends!(spend_txn[0], node_txn[0]);
4980 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4981 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4982 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4983 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4984 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4985 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4987 // Create some initial channels
4988 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4990 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4991 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4992 assert_eq!(revoked_local_txn[0].input.len(), 1);
4993 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4995 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4997 // A will generate HTLC-Timeout from revoked commitment tx
4998 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4999 check_closed_broadcast!(nodes[0], true);
5000 check_added_monitors!(nodes[0], 1);
5001 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5002 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5004 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5005 assert_eq!(revoked_htlc_txn.len(), 2);
5006 check_spends!(revoked_htlc_txn[0], chan_1.3);
5007 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5008 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5009 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5010 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5012 // B will generate justice tx from A's revoked commitment/HTLC tx
5013 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5014 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5015 check_closed_broadcast!(nodes[1], true);
5016 check_added_monitors!(nodes[1], 1);
5017 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5019 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5020 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5021 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5022 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5023 // transactions next...
5024 assert_eq!(node_txn[0].input.len(), 3);
5025 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5027 assert_eq!(node_txn[1].input.len(), 2);
5028 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5029 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5030 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5032 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5033 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5036 assert_eq!(node_txn[2].input.len(), 1);
5037 check_spends!(node_txn[2], chan_1.3);
5039 mine_transaction(&nodes[1], &node_txn[1]);
5040 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5042 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5043 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5044 assert_eq!(spend_txn.len(), 1);
5045 assert_eq!(spend_txn[0].input.len(), 1);
5046 check_spends!(spend_txn[0], node_txn[1]);
5050 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5051 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5052 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5053 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5054 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5055 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5057 // Create some initial channels
5058 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5060 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5061 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5062 assert_eq!(revoked_local_txn[0].input.len(), 1);
5063 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5065 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5066 assert_eq!(revoked_local_txn[0].output.len(), 2);
5068 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5070 // B will generate HTLC-Success from revoked commitment tx
5071 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5072 check_closed_broadcast!(nodes[1], true);
5073 check_added_monitors!(nodes[1], 1);
5074 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5075 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5077 assert_eq!(revoked_htlc_txn.len(), 2);
5078 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5079 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5080 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5082 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5083 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5084 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5086 // A will generate justice tx from B's revoked commitment/HTLC tx
5087 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5088 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5089 check_closed_broadcast!(nodes[0], true);
5090 check_added_monitors!(nodes[0], 1);
5091 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5093 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5094 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5096 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5097 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5098 // transactions next...
5099 assert_eq!(node_txn[0].input.len(), 2);
5100 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5101 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5102 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5104 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5105 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5108 assert_eq!(node_txn[1].input.len(), 1);
5109 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5111 check_spends!(node_txn[2], chan_1.3);
5113 mine_transaction(&nodes[0], &node_txn[1]);
5114 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5116 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5117 // didn't try to generate any new transactions.
5119 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5120 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5121 assert_eq!(spend_txn.len(), 3);
5122 assert_eq!(spend_txn[0].input.len(), 1);
5123 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5124 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5125 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5126 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5130 fn test_onchain_to_onchain_claim() {
5131 // Test that in case of channel closure, we detect the state of output and claim HTLC
5132 // on downstream peer's remote commitment tx.
5133 // First, have C claim an HTLC against its own latest commitment transaction.
5134 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5136 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5139 let chanmon_cfgs = create_chanmon_cfgs(3);
5140 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5141 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5142 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5144 // Create some initial channels
5145 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5146 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5148 // Ensure all nodes are at the same height
5149 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5150 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5151 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5152 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5154 // Rebalance the network a bit by relaying one payment through all the channels ...
5155 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5156 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5158 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5159 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5160 check_spends!(commitment_tx[0], chan_2.3);
5161 nodes[2].node.claim_funds(payment_preimage);
5162 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5163 check_added_monitors!(nodes[2], 1);
5164 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5165 assert!(updates.update_add_htlcs.is_empty());
5166 assert!(updates.update_fail_htlcs.is_empty());
5167 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5168 assert!(updates.update_fail_malformed_htlcs.is_empty());
5170 mine_transaction(&nodes[2], &commitment_tx[0]);
5171 check_closed_broadcast!(nodes[2], true);
5172 check_added_monitors!(nodes[2], 1);
5173 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5175 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5176 assert_eq!(c_txn.len(), 3);
5177 assert_eq!(c_txn[0], c_txn[2]);
5178 assert_eq!(commitment_tx[0], c_txn[1]);
5179 check_spends!(c_txn[1], chan_2.3);
5180 check_spends!(c_txn[2], c_txn[1]);
5181 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5182 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5183 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5184 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5186 // 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
5187 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5188 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5189 check_added_monitors!(nodes[1], 1);
5190 let events = nodes[1].node.get_and_clear_pending_events();
5191 assert_eq!(events.len(), 2);
5193 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5194 _ => panic!("Unexpected event"),
5197 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5198 assert_eq!(fee_earned_msat, Some(1000));
5199 assert_eq!(prev_channel_id, Some(chan_1.2));
5200 assert_eq!(claim_from_onchain_tx, true);
5201 assert_eq!(next_channel_id, Some(chan_2.2));
5203 _ => panic!("Unexpected event"),
5206 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5207 // ChannelMonitor: claim tx
5208 assert_eq!(b_txn.len(), 1);
5209 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5212 check_added_monitors!(nodes[1], 1);
5213 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5214 assert_eq!(msg_events.len(), 3);
5215 match msg_events[0] {
5216 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5217 _ => panic!("Unexpected event"),
5219 match msg_events[1] {
5220 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5221 _ => panic!("Unexpected event"),
5223 match msg_events[2] {
5224 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, .. } } => {
5225 assert!(update_add_htlcs.is_empty());
5226 assert!(update_fail_htlcs.is_empty());
5227 assert_eq!(update_fulfill_htlcs.len(), 1);
5228 assert!(update_fail_malformed_htlcs.is_empty());
5229 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5231 _ => panic!("Unexpected event"),
5233 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5234 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5235 mine_transaction(&nodes[1], &commitment_tx[0]);
5236 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5237 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5238 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5239 assert_eq!(b_txn.len(), 3);
5240 check_spends!(b_txn[1], chan_1.3);
5241 check_spends!(b_txn[2], b_txn[1]);
5242 check_spends!(b_txn[0], commitment_tx[0]);
5243 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5244 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5245 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5247 check_closed_broadcast!(nodes[1], true);
5248 check_added_monitors!(nodes[1], 1);
5252 fn test_duplicate_payment_hash_one_failure_one_success() {
5253 // Topology : A --> B --> C --> D
5254 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5255 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5256 // we forward one of the payments onwards to D.
5257 let chanmon_cfgs = create_chanmon_cfgs(4);
5258 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5259 // When this test was written, the default base fee floated based on the HTLC count.
5260 // It is now fixed, so we simply set the fee to the expected value here.
5261 let mut config = test_default_channel_config();
5262 config.channel_options.forwarding_fee_base_msat = 196;
5263 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5264 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5265 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5267 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5268 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5269 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5271 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5272 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5273 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5274 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5275 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5277 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5279 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5280 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5281 // script push size limit so that the below script length checks match
5282 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5283 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5284 .with_features(InvoiceFeatures::known());
5285 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5286 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5288 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5289 assert_eq!(commitment_txn[0].input.len(), 1);
5290 check_spends!(commitment_txn[0], chan_2.3);
5292 mine_transaction(&nodes[1], &commitment_txn[0]);
5293 check_closed_broadcast!(nodes[1], true);
5294 check_added_monitors!(nodes[1], 1);
5295 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5296 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5298 let htlc_timeout_tx;
5299 { // Extract one of the two HTLC-Timeout transaction
5300 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5301 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5302 assert_eq!(node_txn.len(), 4);
5303 check_spends!(node_txn[0], chan_2.3);
5305 check_spends!(node_txn[1], commitment_txn[0]);
5306 assert_eq!(node_txn[1].input.len(), 1);
5307 check_spends!(node_txn[2], commitment_txn[0]);
5308 assert_eq!(node_txn[2].input.len(), 1);
5309 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5310 check_spends!(node_txn[3], commitment_txn[0]);
5311 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].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 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5316 htlc_timeout_tx = node_txn[1].clone();
5319 nodes[2].node.claim_funds(our_payment_preimage);
5320 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5322 mine_transaction(&nodes[2], &commitment_txn[0]);
5323 check_added_monitors!(nodes[2], 2);
5324 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5325 let events = nodes[2].node.get_and_clear_pending_msg_events();
5327 MessageSendEvent::UpdateHTLCs { .. } => {},
5328 _ => panic!("Unexpected event"),
5331 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5332 _ => panic!("Unexepected event"),
5334 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5335 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)
5336 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5337 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5338 assert_eq!(htlc_success_txn[0].input.len(), 1);
5339 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5340 assert_eq!(htlc_success_txn[1].input.len(), 1);
5341 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5342 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5343 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5344 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5345 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5346 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5348 mine_transaction(&nodes[1], &htlc_timeout_tx);
5349 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5350 expect_pending_htlcs_forwardable!(nodes[1]);
5351 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5352 assert!(htlc_updates.update_add_htlcs.is_empty());
5353 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5354 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5355 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5356 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5357 check_added_monitors!(nodes[1], 1);
5359 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5360 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5362 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5364 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5366 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5367 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5368 // and nodes[2] fee) is rounded down and then claimed in full.
5369 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5370 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5371 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5372 assert!(updates.update_add_htlcs.is_empty());
5373 assert!(updates.update_fail_htlcs.is_empty());
5374 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5375 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5376 assert!(updates.update_fail_malformed_htlcs.is_empty());
5377 check_added_monitors!(nodes[1], 1);
5379 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5380 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5382 let events = nodes[0].node.get_and_clear_pending_events();
5384 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5385 assert_eq!(*payment_preimage, our_payment_preimage);
5386 assert_eq!(*payment_hash, duplicate_payment_hash);
5388 _ => panic!("Unexpected event"),
5393 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5394 let chanmon_cfgs = create_chanmon_cfgs(2);
5395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5399 // Create some initial channels
5400 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5402 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5403 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5404 assert_eq!(local_txn.len(), 1);
5405 assert_eq!(local_txn[0].input.len(), 1);
5406 check_spends!(local_txn[0], chan_1.3);
5408 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5409 nodes[1].node.claim_funds(payment_preimage);
5410 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5411 check_added_monitors!(nodes[1], 1);
5413 mine_transaction(&nodes[1], &local_txn[0]);
5414 check_added_monitors!(nodes[1], 1);
5415 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5416 let events = nodes[1].node.get_and_clear_pending_msg_events();
5418 MessageSendEvent::UpdateHTLCs { .. } => {},
5419 _ => panic!("Unexpected event"),
5422 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5423 _ => panic!("Unexepected event"),
5426 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5427 assert_eq!(node_txn.len(), 3);
5428 assert_eq!(node_txn[0], node_txn[2]);
5429 assert_eq!(node_txn[1], local_txn[0]);
5430 assert_eq!(node_txn[0].input.len(), 1);
5431 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5432 check_spends!(node_txn[0], local_txn[0]);
5436 mine_transaction(&nodes[1], &node_tx);
5437 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5439 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5440 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5441 assert_eq!(spend_txn.len(), 1);
5442 assert_eq!(spend_txn[0].input.len(), 1);
5443 check_spends!(spend_txn[0], node_tx);
5444 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5447 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5448 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5449 // unrevoked commitment transaction.
5450 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5451 // a remote RAA before they could be failed backwards (and combinations thereof).
5452 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5453 // use the same payment hashes.
5454 // Thus, we use a six-node network:
5459 // And test where C fails back to A/B when D announces its latest commitment transaction
5460 let chanmon_cfgs = create_chanmon_cfgs(6);
5461 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5462 // When this test was written, the default base fee floated based on the HTLC count.
5463 // It is now fixed, so we simply set the fee to the expected value here.
5464 let mut config = test_default_channel_config();
5465 config.channel_options.forwarding_fee_base_msat = 196;
5466 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5467 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5468 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5470 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5471 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5472 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5473 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5474 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5476 // Rebalance and check output sanity...
5477 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5478 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5479 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5481 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5483 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
5485 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
5486 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5488 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
5490 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
5492 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5494 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5495 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5497 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());
5499 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());
5502 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5504 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5505 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
5508 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
5510 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5511 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());
5513 // Double-check that six of the new HTLC were added
5514 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5515 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5516 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5517 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5519 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5520 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5521 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5522 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5523 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5524 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5525 check_added_monitors!(nodes[4], 0);
5526 expect_pending_htlcs_forwardable!(nodes[4]);
5527 check_added_monitors!(nodes[4], 1);
5529 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5530 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5531 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5532 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5533 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5534 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5536 // Fail 3rd below-dust and 7th above-dust HTLCs
5537 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5538 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5539 check_added_monitors!(nodes[5], 0);
5540 expect_pending_htlcs_forwardable!(nodes[5]);
5541 check_added_monitors!(nodes[5], 1);
5543 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5544 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5545 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5546 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5548 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5550 expect_pending_htlcs_forwardable!(nodes[3]);
5551 check_added_monitors!(nodes[3], 1);
5552 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5553 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5554 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5555 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5556 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5557 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5558 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5559 if deliver_last_raa {
5560 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5562 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5565 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5566 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5567 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5568 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5570 // We now broadcast the latest commitment transaction, which *should* result in failures for
5571 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5572 // the non-broadcast above-dust HTLCs.
5574 // Alternatively, we may broadcast the previous commitment transaction, which should only
5575 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5576 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5578 if announce_latest {
5579 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5581 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5583 let events = nodes[2].node.get_and_clear_pending_events();
5584 let close_event = if deliver_last_raa {
5585 assert_eq!(events.len(), 2);
5588 assert_eq!(events.len(), 1);
5592 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5593 _ => panic!("Unexpected event"),
5596 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5597 check_closed_broadcast!(nodes[2], true);
5598 if deliver_last_raa {
5599 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5601 expect_pending_htlcs_forwardable!(nodes[2]);
5603 check_added_monitors!(nodes[2], 3);
5605 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5606 assert_eq!(cs_msgs.len(), 2);
5607 let mut a_done = false;
5608 for msg in cs_msgs {
5610 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5611 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5612 // should be failed-backwards here.
5613 let target = if *node_id == nodes[0].node.get_our_node_id() {
5614 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5615 for htlc in &updates.update_fail_htlcs {
5616 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 });
5618 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5623 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5624 for htlc in &updates.update_fail_htlcs {
5625 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5627 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5628 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5631 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5632 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5633 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5634 if announce_latest {
5635 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5636 if *node_id == nodes[0].node.get_our_node_id() {
5637 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5640 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5642 _ => panic!("Unexpected event"),
5646 let as_events = nodes[0].node.get_and_clear_pending_events();
5647 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5648 let mut as_failds = HashSet::new();
5649 let mut as_updates = 0;
5650 for event in as_events.iter() {
5651 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5652 assert!(as_failds.insert(*payment_hash));
5653 if *payment_hash != payment_hash_2 {
5654 assert_eq!(*rejected_by_dest, deliver_last_raa);
5656 assert!(!rejected_by_dest);
5658 if network_update.is_some() {
5661 } else { panic!("Unexpected event"); }
5663 assert!(as_failds.contains(&payment_hash_1));
5664 assert!(as_failds.contains(&payment_hash_2));
5665 if announce_latest {
5666 assert!(as_failds.contains(&payment_hash_3));
5667 assert!(as_failds.contains(&payment_hash_5));
5669 assert!(as_failds.contains(&payment_hash_6));
5671 let bs_events = nodes[1].node.get_and_clear_pending_events();
5672 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5673 let mut bs_failds = HashSet::new();
5674 let mut bs_updates = 0;
5675 for event in bs_events.iter() {
5676 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5677 assert!(bs_failds.insert(*payment_hash));
5678 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5679 assert_eq!(*rejected_by_dest, deliver_last_raa);
5681 assert!(!rejected_by_dest);
5683 if network_update.is_some() {
5686 } else { panic!("Unexpected event"); }
5688 assert!(bs_failds.contains(&payment_hash_1));
5689 assert!(bs_failds.contains(&payment_hash_2));
5690 if announce_latest {
5691 assert!(bs_failds.contains(&payment_hash_4));
5693 assert!(bs_failds.contains(&payment_hash_5));
5695 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5696 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5697 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5698 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5699 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5700 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5704 fn test_fail_backwards_latest_remote_announce_a() {
5705 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5709 fn test_fail_backwards_latest_remote_announce_b() {
5710 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5714 fn test_fail_backwards_previous_remote_announce() {
5715 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5716 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5717 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5721 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5722 let chanmon_cfgs = create_chanmon_cfgs(2);
5723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5727 // Create some initial channels
5728 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5730 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5731 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5732 assert_eq!(local_txn[0].input.len(), 1);
5733 check_spends!(local_txn[0], chan_1.3);
5735 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5736 mine_transaction(&nodes[0], &local_txn[0]);
5737 check_closed_broadcast!(nodes[0], true);
5738 check_added_monitors!(nodes[0], 1);
5739 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5740 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5742 let htlc_timeout = {
5743 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5744 assert_eq!(node_txn.len(), 2);
5745 check_spends!(node_txn[0], chan_1.3);
5746 assert_eq!(node_txn[1].input.len(), 1);
5747 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5748 check_spends!(node_txn[1], local_txn[0]);
5752 mine_transaction(&nodes[0], &htlc_timeout);
5753 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5754 expect_payment_failed!(nodes[0], our_payment_hash, true);
5756 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5757 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5758 assert_eq!(spend_txn.len(), 3);
5759 check_spends!(spend_txn[0], local_txn[0]);
5760 assert_eq!(spend_txn[1].input.len(), 1);
5761 check_spends!(spend_txn[1], htlc_timeout);
5762 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5763 assert_eq!(spend_txn[2].input.len(), 2);
5764 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5765 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5766 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5770 fn test_key_derivation_params() {
5771 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5772 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5773 // let us re-derive the channel key set to then derive a delayed_payment_key.
5775 let chanmon_cfgs = create_chanmon_cfgs(3);
5777 // We manually create the node configuration to backup the seed.
5778 let seed = [42; 32];
5779 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5780 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);
5781 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: &chanmon_cfgs[0].network_graph, node_seed: seed, features: InitFeatures::known() };
5782 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5783 node_cfgs.remove(0);
5784 node_cfgs.insert(0, node);
5786 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5787 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5789 // Create some initial channels
5790 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5792 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5793 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5794 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5796 // Ensure all nodes are at the same height
5797 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5798 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5799 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5800 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5802 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5803 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5804 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5805 assert_eq!(local_txn_1[0].input.len(), 1);
5806 check_spends!(local_txn_1[0], chan_1.3);
5808 // We check funding pubkey are unique
5809 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]));
5810 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]));
5811 if from_0_funding_key_0 == from_1_funding_key_0
5812 || from_0_funding_key_0 == from_1_funding_key_1
5813 || from_0_funding_key_1 == from_1_funding_key_0
5814 || from_0_funding_key_1 == from_1_funding_key_1 {
5815 panic!("Funding pubkeys aren't unique");
5818 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5819 mine_transaction(&nodes[0], &local_txn_1[0]);
5820 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5821 check_closed_broadcast!(nodes[0], true);
5822 check_added_monitors!(nodes[0], 1);
5823 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5825 let htlc_timeout = {
5826 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5827 assert_eq!(node_txn[1].input.len(), 1);
5828 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5829 check_spends!(node_txn[1], local_txn_1[0]);
5833 mine_transaction(&nodes[0], &htlc_timeout);
5834 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5835 expect_payment_failed!(nodes[0], our_payment_hash, true);
5837 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5838 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5839 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5840 assert_eq!(spend_txn.len(), 3);
5841 check_spends!(spend_txn[0], local_txn_1[0]);
5842 assert_eq!(spend_txn[1].input.len(), 1);
5843 check_spends!(spend_txn[1], htlc_timeout);
5844 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5845 assert_eq!(spend_txn[2].input.len(), 2);
5846 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5847 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5848 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5852 fn test_static_output_closing_tx() {
5853 let chanmon_cfgs = create_chanmon_cfgs(2);
5854 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5855 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5856 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5858 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5860 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5861 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5863 mine_transaction(&nodes[0], &closing_tx);
5864 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5865 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5867 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5868 assert_eq!(spend_txn.len(), 1);
5869 check_spends!(spend_txn[0], closing_tx);
5871 mine_transaction(&nodes[1], &closing_tx);
5872 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5873 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5875 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5876 assert_eq!(spend_txn.len(), 1);
5877 check_spends!(spend_txn[0], closing_tx);
5880 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5881 let chanmon_cfgs = create_chanmon_cfgs(2);
5882 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5883 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5884 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5885 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5887 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5889 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5890 // present in B's local commitment transaction, but none of A's commitment transactions.
5891 nodes[1].node.claim_funds(payment_preimage);
5892 check_added_monitors!(nodes[1], 1);
5893 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5895 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5896 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5897 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5899 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5900 check_added_monitors!(nodes[0], 1);
5901 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5902 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5903 check_added_monitors!(nodes[1], 1);
5905 let starting_block = nodes[1].best_block_info();
5906 let mut block = Block {
5907 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5910 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5911 connect_block(&nodes[1], &block);
5912 block.header.prev_blockhash = block.block_hash();
5914 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5915 check_closed_broadcast!(nodes[1], true);
5916 check_added_monitors!(nodes[1], 1);
5917 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5920 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5921 let chanmon_cfgs = create_chanmon_cfgs(2);
5922 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5923 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5924 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5925 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5927 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5928 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5929 check_added_monitors!(nodes[0], 1);
5931 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5933 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5934 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5935 // to "time out" the HTLC.
5937 let starting_block = nodes[1].best_block_info();
5938 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5940 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5941 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5942 header.prev_blockhash = header.block_hash();
5944 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5945 check_closed_broadcast!(nodes[0], true);
5946 check_added_monitors!(nodes[0], 1);
5947 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5950 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5951 let chanmon_cfgs = create_chanmon_cfgs(3);
5952 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5953 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5954 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5955 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5957 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5958 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5959 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5960 // actually revoked.
5961 let htlc_value = if use_dust { 50000 } else { 3000000 };
5962 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5963 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5964 expect_pending_htlcs_forwardable!(nodes[1]);
5965 check_added_monitors!(nodes[1], 1);
5967 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5968 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5969 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5970 check_added_monitors!(nodes[0], 1);
5971 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5972 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5973 check_added_monitors!(nodes[1], 1);
5974 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5975 check_added_monitors!(nodes[1], 1);
5976 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5978 if check_revoke_no_close {
5979 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5980 check_added_monitors!(nodes[0], 1);
5983 let starting_block = nodes[1].best_block_info();
5984 let mut block = Block {
5985 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5988 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5989 connect_block(&nodes[0], &block);
5990 block.header.prev_blockhash = block.block_hash();
5992 if !check_revoke_no_close {
5993 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5994 check_closed_broadcast!(nodes[0], true);
5995 check_added_monitors!(nodes[0], 1);
5996 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5998 let events = nodes[0].node.get_and_clear_pending_events();
5999 assert_eq!(events.len(), 2);
6000 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6001 assert_eq!(*payment_hash, our_payment_hash);
6002 } else { panic!("Unexpected event"); }
6003 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6004 assert_eq!(*payment_hash, our_payment_hash);
6005 } else { panic!("Unexpected event"); }
6009 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6010 // There are only a few cases to test here:
6011 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6012 // broadcastable commitment transactions result in channel closure,
6013 // * its included in an unrevoked-but-previous remote commitment transaction,
6014 // * its included in the latest remote or local commitment transactions.
6015 // We test each of the three possible commitment transactions individually and use both dust and
6017 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6018 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6019 // tested for at least one of the cases in other tests.
6021 fn htlc_claim_single_commitment_only_a() {
6022 do_htlc_claim_local_commitment_only(true);
6023 do_htlc_claim_local_commitment_only(false);
6025 do_htlc_claim_current_remote_commitment_only(true);
6026 do_htlc_claim_current_remote_commitment_only(false);
6030 fn htlc_claim_single_commitment_only_b() {
6031 do_htlc_claim_previous_remote_commitment_only(true, false);
6032 do_htlc_claim_previous_remote_commitment_only(false, false);
6033 do_htlc_claim_previous_remote_commitment_only(true, true);
6034 do_htlc_claim_previous_remote_commitment_only(false, true);
6039 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6040 let chanmon_cfgs = create_chanmon_cfgs(2);
6041 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6042 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6043 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6044 // Force duplicate randomness for every get-random call
6045 for node in nodes.iter() {
6046 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6049 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6050 let channel_value_satoshis=10000;
6051 let push_msat=10001;
6052 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6053 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6054 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6055 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6057 // Create a second channel with the same random values. This used to panic due to a colliding
6058 // channel_id, but now panics due to a colliding outbound SCID alias.
6059 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6063 fn bolt2_open_channel_sending_node_checks_part2() {
6064 let chanmon_cfgs = create_chanmon_cfgs(2);
6065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6067 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6069 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6070 let channel_value_satoshis=2^24;
6071 let push_msat=10001;
6072 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6074 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6075 let channel_value_satoshis=10000;
6076 // Test when push_msat is equal to 1000 * funding_satoshis.
6077 let push_msat=1000*channel_value_satoshis+1;
6078 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6080 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6081 let channel_value_satoshis=10000;
6082 let push_msat=10001;
6083 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
6084 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6085 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6087 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6088 // 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
6089 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6091 // 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.
6092 assert!(BREAKDOWN_TIMEOUT>0);
6093 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6095 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6096 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6097 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6099 // 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.
6100 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6101 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6102 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6103 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6104 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6108 fn bolt2_open_channel_sane_dust_limit() {
6109 let chanmon_cfgs = create_chanmon_cfgs(2);
6110 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6111 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6112 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6114 let channel_value_satoshis=1000000;
6115 let push_msat=10001;
6116 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6117 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6118 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6119 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6121 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6122 let events = nodes[1].node.get_and_clear_pending_msg_events();
6123 let err_msg = match events[0] {
6124 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6127 _ => panic!("Unexpected event"),
6129 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6132 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6133 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6134 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6135 // is no longer affordable once it's freed.
6137 fn test_fail_holding_cell_htlc_upon_free() {
6138 let chanmon_cfgs = create_chanmon_cfgs(2);
6139 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6140 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6141 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6142 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6144 // First nodes[0] generates an update_fee, setting the channel's
6145 // pending_update_fee.
6147 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6148 *feerate_lock += 20;
6150 nodes[0].node.timer_tick_occurred();
6151 check_added_monitors!(nodes[0], 1);
6153 let events = nodes[0].node.get_and_clear_pending_msg_events();
6154 assert_eq!(events.len(), 1);
6155 let (update_msg, commitment_signed) = match events[0] {
6156 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6157 (update_fee.as_ref(), commitment_signed)
6159 _ => panic!("Unexpected event"),
6162 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6164 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6165 let channel_reserve = chan_stat.channel_reserve_msat;
6166 let feerate = get_feerate!(nodes[0], chan.2);
6167 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6169 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6170 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6171 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6173 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6174 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6175 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6176 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6178 // Flush the pending fee update.
6179 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6180 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6181 check_added_monitors!(nodes[1], 1);
6182 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6183 check_added_monitors!(nodes[0], 1);
6185 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6186 // HTLC, but now that the fee has been raised the payment will now fail, causing
6187 // us to surface its failure to the user.
6188 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6189 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6190 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);
6191 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 {}",
6192 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6193 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6195 // Check that the payment failed to be sent out.
6196 let events = nodes[0].node.get_and_clear_pending_events();
6197 assert_eq!(events.len(), 1);
6199 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6200 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6201 assert_eq!(our_payment_hash.clone(), *payment_hash);
6202 assert_eq!(*rejected_by_dest, false);
6203 assert_eq!(*all_paths_failed, true);
6204 assert_eq!(*network_update, None);
6205 assert_eq!(*short_channel_id, None);
6206 assert_eq!(*error_code, None);
6207 assert_eq!(*error_data, None);
6209 _ => panic!("Unexpected event"),
6213 // Test that if multiple HTLCs are released from the holding cell and one is
6214 // valid but the other is no longer valid upon release, the valid HTLC can be
6215 // successfully completed while the other one fails as expected.
6217 fn test_free_and_fail_holding_cell_htlcs() {
6218 let chanmon_cfgs = create_chanmon_cfgs(2);
6219 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6220 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6221 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6222 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6224 // First nodes[0] generates an update_fee, setting the channel's
6225 // pending_update_fee.
6227 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6228 *feerate_lock += 200;
6230 nodes[0].node.timer_tick_occurred();
6231 check_added_monitors!(nodes[0], 1);
6233 let events = nodes[0].node.get_and_clear_pending_msg_events();
6234 assert_eq!(events.len(), 1);
6235 let (update_msg, commitment_signed) = match events[0] {
6236 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6237 (update_fee.as_ref(), commitment_signed)
6239 _ => panic!("Unexpected event"),
6242 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6244 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6245 let channel_reserve = chan_stat.channel_reserve_msat;
6246 let feerate = get_feerate!(nodes[0], chan.2);
6247 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6249 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6251 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6252 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6253 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6255 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6256 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6257 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6258 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6259 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6260 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6261 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6263 // Flush the pending fee update.
6264 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6265 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6266 check_added_monitors!(nodes[1], 1);
6267 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6268 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6269 check_added_monitors!(nodes[0], 2);
6271 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6272 // but now that the fee has been raised the second payment will now fail, causing us
6273 // to surface its failure to the user. The first payment should succeed.
6274 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6275 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6276 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);
6277 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 {}",
6278 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6279 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6281 // Check that the second payment failed to be sent out.
6282 let events = nodes[0].node.get_and_clear_pending_events();
6283 assert_eq!(events.len(), 1);
6285 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6286 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6287 assert_eq!(payment_hash_2.clone(), *payment_hash);
6288 assert_eq!(*rejected_by_dest, false);
6289 assert_eq!(*all_paths_failed, true);
6290 assert_eq!(*network_update, None);
6291 assert_eq!(*short_channel_id, None);
6292 assert_eq!(*error_code, None);
6293 assert_eq!(*error_data, None);
6295 _ => panic!("Unexpected event"),
6298 // Complete the first payment and the RAA from the fee update.
6299 let (payment_event, send_raa_event) = {
6300 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6301 assert_eq!(msgs.len(), 2);
6302 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6304 let raa = match send_raa_event {
6305 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6306 _ => panic!("Unexpected event"),
6308 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6309 check_added_monitors!(nodes[1], 1);
6310 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6311 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6312 let events = nodes[1].node.get_and_clear_pending_events();
6313 assert_eq!(events.len(), 1);
6315 Event::PendingHTLCsForwardable { .. } => {},
6316 _ => panic!("Unexpected event"),
6318 nodes[1].node.process_pending_htlc_forwards();
6319 let events = nodes[1].node.get_and_clear_pending_events();
6320 assert_eq!(events.len(), 1);
6322 Event::PaymentReceived { .. } => {},
6323 _ => panic!("Unexpected event"),
6325 nodes[1].node.claim_funds(payment_preimage_1);
6326 check_added_monitors!(nodes[1], 1);
6327 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6329 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6330 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6331 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6332 expect_payment_sent!(nodes[0], payment_preimage_1);
6335 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6336 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6337 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6340 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6341 let chanmon_cfgs = create_chanmon_cfgs(3);
6342 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6343 // When this test was written, the default base fee floated based on the HTLC count.
6344 // It is now fixed, so we simply set the fee to the expected value here.
6345 let mut config = test_default_channel_config();
6346 config.channel_options.forwarding_fee_base_msat = 196;
6347 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6348 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6349 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6350 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6352 // First nodes[1] generates an update_fee, setting the channel's
6353 // pending_update_fee.
6355 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6356 *feerate_lock += 20;
6358 nodes[1].node.timer_tick_occurred();
6359 check_added_monitors!(nodes[1], 1);
6361 let events = nodes[1].node.get_and_clear_pending_msg_events();
6362 assert_eq!(events.len(), 1);
6363 let (update_msg, commitment_signed) = match events[0] {
6364 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6365 (update_fee.as_ref(), commitment_signed)
6367 _ => panic!("Unexpected event"),
6370 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6372 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6373 let channel_reserve = chan_stat.channel_reserve_msat;
6374 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6375 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6377 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6379 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6380 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6381 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6382 let payment_event = {
6383 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6384 check_added_monitors!(nodes[0], 1);
6386 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6387 assert_eq!(events.len(), 1);
6389 SendEvent::from_event(events.remove(0))
6391 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6392 check_added_monitors!(nodes[1], 0);
6393 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6394 expect_pending_htlcs_forwardable!(nodes[1]);
6396 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6397 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6399 // Flush the pending fee update.
6400 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6401 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6402 check_added_monitors!(nodes[2], 1);
6403 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6404 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6405 check_added_monitors!(nodes[1], 2);
6407 // A final RAA message is generated to finalize the fee update.
6408 let events = nodes[1].node.get_and_clear_pending_msg_events();
6409 assert_eq!(events.len(), 1);
6411 let raa_msg = match &events[0] {
6412 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6415 _ => panic!("Unexpected event"),
6418 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6419 check_added_monitors!(nodes[2], 1);
6420 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6422 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6423 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6424 assert_eq!(process_htlc_forwards_event.len(), 1);
6425 match &process_htlc_forwards_event[0] {
6426 &Event::PendingHTLCsForwardable { .. } => {},
6427 _ => panic!("Unexpected event"),
6430 // In response, we call ChannelManager's process_pending_htlc_forwards
6431 nodes[1].node.process_pending_htlc_forwards();
6432 check_added_monitors!(nodes[1], 1);
6434 // This causes the HTLC to be failed backwards.
6435 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6436 assert_eq!(fail_event.len(), 1);
6437 let (fail_msg, commitment_signed) = match &fail_event[0] {
6438 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6439 assert_eq!(updates.update_add_htlcs.len(), 0);
6440 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6441 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6442 assert_eq!(updates.update_fail_htlcs.len(), 1);
6443 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6445 _ => panic!("Unexpected event"),
6448 // Pass the failure messages back to nodes[0].
6449 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6450 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6452 // Complete the HTLC failure+removal process.
6453 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6454 check_added_monitors!(nodes[0], 1);
6455 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6456 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6457 check_added_monitors!(nodes[1], 2);
6458 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6459 assert_eq!(final_raa_event.len(), 1);
6460 let raa = match &final_raa_event[0] {
6461 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6462 _ => panic!("Unexpected event"),
6464 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6465 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6466 check_added_monitors!(nodes[0], 1);
6469 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6470 // 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.
6471 //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.
6474 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6475 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6476 let chanmon_cfgs = create_chanmon_cfgs(2);
6477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6479 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6480 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6482 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6483 route.paths[0][0].fee_msat = 100;
6485 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6486 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6487 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6488 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6492 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6493 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6494 let chanmon_cfgs = create_chanmon_cfgs(2);
6495 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6496 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6497 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6498 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6500 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6501 route.paths[0][0].fee_msat = 0;
6502 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6503 assert_eq!(err, "Cannot send 0-msat HTLC"));
6505 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6506 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6510 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6511 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6512 let chanmon_cfgs = create_chanmon_cfgs(2);
6513 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6514 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6515 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6516 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6518 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6519 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6520 check_added_monitors!(nodes[0], 1);
6521 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6522 updates.update_add_htlcs[0].amount_msat = 0;
6524 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6525 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6526 check_closed_broadcast!(nodes[1], true).unwrap();
6527 check_added_monitors!(nodes[1], 1);
6528 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6532 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6533 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6534 //It is enforced when constructing a route.
6535 let chanmon_cfgs = create_chanmon_cfgs(2);
6536 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6537 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6538 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6539 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6541 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6542 .with_features(InvoiceFeatures::known());
6543 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6544 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6545 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6546 assert_eq!(err, &"Channel CLTV overflowed?"));
6550 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6551 //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.
6552 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6553 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6554 let chanmon_cfgs = create_chanmon_cfgs(2);
6555 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6556 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6557 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6558 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6559 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6561 for i in 0..max_accepted_htlcs {
6562 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6563 let payment_event = {
6564 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6565 check_added_monitors!(nodes[0], 1);
6567 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6568 assert_eq!(events.len(), 1);
6569 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6570 assert_eq!(htlcs[0].htlc_id, i);
6574 SendEvent::from_event(events.remove(0))
6576 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6577 check_added_monitors!(nodes[1], 0);
6578 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6580 expect_pending_htlcs_forwardable!(nodes[1]);
6581 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6583 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6584 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6585 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6587 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6588 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6592 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6593 //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.
6594 let chanmon_cfgs = create_chanmon_cfgs(2);
6595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6598 let channel_value = 100000;
6599 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6600 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6602 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6604 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6605 // Manually create a route over our max in flight (which our router normally automatically
6607 route.paths[0][0].fee_msat = max_in_flight + 1;
6608 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6609 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)));
6611 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6612 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);
6614 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6617 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6619 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6620 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6621 let chanmon_cfgs = create_chanmon_cfgs(2);
6622 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6623 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6624 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6625 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6626 let htlc_minimum_msat: u64;
6628 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6629 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6630 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6633 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6634 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6635 check_added_monitors!(nodes[0], 1);
6636 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6637 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6638 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6639 assert!(nodes[1].node.list_channels().is_empty());
6640 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6641 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()));
6642 check_added_monitors!(nodes[1], 1);
6643 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6647 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6648 //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
6649 let chanmon_cfgs = create_chanmon_cfgs(2);
6650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6652 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6655 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6656 let channel_reserve = chan_stat.channel_reserve_msat;
6657 let feerate = get_feerate!(nodes[0], chan.2);
6658 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6659 // The 2* and +1 are for the fee spike reserve.
6660 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6662 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6663 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6664 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6665 check_added_monitors!(nodes[0], 1);
6666 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6668 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6669 // at this time channel-initiatee receivers are not required to enforce that senders
6670 // respect the fee_spike_reserve.
6671 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6672 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6674 assert!(nodes[1].node.list_channels().is_empty());
6675 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6676 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6677 check_added_monitors!(nodes[1], 1);
6678 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6682 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6683 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6684 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6685 let chanmon_cfgs = create_chanmon_cfgs(2);
6686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6688 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6689 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6691 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6692 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6693 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6694 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6695 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6696 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6698 let mut msg = msgs::UpdateAddHTLC {
6702 payment_hash: our_payment_hash,
6703 cltv_expiry: htlc_cltv,
6704 onion_routing_packet: onion_packet.clone(),
6707 for i in 0..super::channel::OUR_MAX_HTLCS {
6708 msg.htlc_id = i as u64;
6709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6711 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6712 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6714 assert!(nodes[1].node.list_channels().is_empty());
6715 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6716 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6717 check_added_monitors!(nodes[1], 1);
6718 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6722 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6723 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6724 let chanmon_cfgs = create_chanmon_cfgs(2);
6725 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6726 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6727 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6728 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6730 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6731 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6732 check_added_monitors!(nodes[0], 1);
6733 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6734 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6735 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6737 assert!(nodes[1].node.list_channels().is_empty());
6738 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6739 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6740 check_added_monitors!(nodes[1], 1);
6741 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6745 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6746 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6747 let chanmon_cfgs = create_chanmon_cfgs(2);
6748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6750 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6752 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6753 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6754 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6755 check_added_monitors!(nodes[0], 1);
6756 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6757 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6758 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6760 assert!(nodes[1].node.list_channels().is_empty());
6761 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6762 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6763 check_added_monitors!(nodes[1], 1);
6764 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6768 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6769 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6770 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6771 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6772 let chanmon_cfgs = create_chanmon_cfgs(2);
6773 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6774 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6775 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6777 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6778 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6779 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6780 check_added_monitors!(nodes[0], 1);
6781 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6782 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6784 //Disconnect and Reconnect
6785 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6786 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6787 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6788 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6789 assert_eq!(reestablish_1.len(), 1);
6790 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6791 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6792 assert_eq!(reestablish_2.len(), 1);
6793 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6794 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6795 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6796 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6799 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6800 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6801 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6802 check_added_monitors!(nodes[1], 1);
6803 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6805 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6807 assert!(nodes[1].node.list_channels().is_empty());
6808 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6809 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6810 check_added_monitors!(nodes[1], 1);
6811 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6815 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6816 //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.
6818 let chanmon_cfgs = create_chanmon_cfgs(2);
6819 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6820 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6821 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6822 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6823 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6824 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6826 check_added_monitors!(nodes[0], 1);
6827 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6828 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6830 let update_msg = msgs::UpdateFulfillHTLC{
6833 payment_preimage: our_payment_preimage,
6836 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6838 assert!(nodes[0].node.list_channels().is_empty());
6839 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6840 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()));
6841 check_added_monitors!(nodes[0], 1);
6842 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6846 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6847 //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.
6849 let chanmon_cfgs = create_chanmon_cfgs(2);
6850 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6851 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6852 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6853 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6855 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6856 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6857 check_added_monitors!(nodes[0], 1);
6858 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6859 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6861 let update_msg = msgs::UpdateFailHTLC{
6864 reason: msgs::OnionErrorPacket { data: Vec::new()},
6867 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6869 assert!(nodes[0].node.list_channels().is_empty());
6870 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6871 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()));
6872 check_added_monitors!(nodes[0], 1);
6873 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6877 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6878 //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions: MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6880 let chanmon_cfgs = create_chanmon_cfgs(2);
6881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6883 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6884 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6886 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6887 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6888 check_added_monitors!(nodes[0], 1);
6889 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6890 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6891 let update_msg = msgs::UpdateFailMalformedHTLC{
6894 sha256_of_onion: [1; 32],
6895 failure_code: 0x8000,
6898 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6900 assert!(nodes[0].node.list_channels().is_empty());
6901 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6902 assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6903 check_added_monitors!(nodes[0], 1);
6904 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6908 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6909 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6911 let chanmon_cfgs = create_chanmon_cfgs(2);
6912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6914 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6915 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6917 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6919 nodes[1].node.claim_funds(our_payment_preimage);
6920 check_added_monitors!(nodes[1], 1);
6921 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6923 let events = nodes[1].node.get_and_clear_pending_msg_events();
6924 assert_eq!(events.len(), 1);
6925 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6927 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, .. } } => {
6928 assert!(update_add_htlcs.is_empty());
6929 assert_eq!(update_fulfill_htlcs.len(), 1);
6930 assert!(update_fail_htlcs.is_empty());
6931 assert!(update_fail_malformed_htlcs.is_empty());
6932 assert!(update_fee.is_none());
6933 update_fulfill_htlcs[0].clone()
6935 _ => panic!("Unexpected event"),
6939 update_fulfill_msg.htlc_id = 1;
6941 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6943 assert!(nodes[0].node.list_channels().is_empty());
6944 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6945 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6946 check_added_monitors!(nodes[0], 1);
6947 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6951 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6952 //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.
6954 let chanmon_cfgs = create_chanmon_cfgs(2);
6955 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6956 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6957 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6958 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6960 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6962 nodes[1].node.claim_funds(our_payment_preimage);
6963 check_added_monitors!(nodes[1], 1);
6964 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6966 let events = nodes[1].node.get_and_clear_pending_msg_events();
6967 assert_eq!(events.len(), 1);
6968 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6970 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, .. } } => {
6971 assert!(update_add_htlcs.is_empty());
6972 assert_eq!(update_fulfill_htlcs.len(), 1);
6973 assert!(update_fail_htlcs.is_empty());
6974 assert!(update_fail_malformed_htlcs.is_empty());
6975 assert!(update_fee.is_none());
6976 update_fulfill_htlcs[0].clone()
6978 _ => panic!("Unexpected event"),
6982 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6984 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6986 assert!(nodes[0].node.list_channels().is_empty());
6987 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6988 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6989 check_added_monitors!(nodes[0], 1);
6990 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6994 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6995 //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.
6997 let chanmon_cfgs = create_chanmon_cfgs(2);
6998 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6999 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7000 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7001 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7003 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7004 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7005 check_added_monitors!(nodes[0], 1);
7007 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7008 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7010 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7011 check_added_monitors!(nodes[1], 0);
7012 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7014 let events = nodes[1].node.get_and_clear_pending_msg_events();
7016 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7018 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, .. } } => {
7019 assert!(update_add_htlcs.is_empty());
7020 assert!(update_fulfill_htlcs.is_empty());
7021 assert!(update_fail_htlcs.is_empty());
7022 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7023 assert!(update_fee.is_none());
7024 update_fail_malformed_htlcs[0].clone()
7026 _ => panic!("Unexpected event"),
7029 update_msg.failure_code &= !0x8000;
7030 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7032 assert!(nodes[0].node.list_channels().is_empty());
7033 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7034 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7035 check_added_monitors!(nodes[0], 1);
7036 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7040 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7041 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7042 // * 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.
7044 let chanmon_cfgs = create_chanmon_cfgs(3);
7045 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7046 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7047 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7048 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7049 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7051 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7054 let mut payment_event = {
7055 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7056 check_added_monitors!(nodes[0], 1);
7057 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7058 assert_eq!(events.len(), 1);
7059 SendEvent::from_event(events.remove(0))
7061 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7062 check_added_monitors!(nodes[1], 0);
7063 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7064 expect_pending_htlcs_forwardable!(nodes[1]);
7065 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7066 assert_eq!(events_2.len(), 1);
7067 check_added_monitors!(nodes[1], 1);
7068 payment_event = SendEvent::from_event(events_2.remove(0));
7069 assert_eq!(payment_event.msgs.len(), 1);
7072 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7073 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7074 check_added_monitors!(nodes[2], 0);
7075 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7077 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7078 assert_eq!(events_3.len(), 1);
7079 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7081 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 } } => {
7082 assert!(update_add_htlcs.is_empty());
7083 assert!(update_fulfill_htlcs.is_empty());
7084 assert!(update_fail_htlcs.is_empty());
7085 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7086 assert!(update_fee.is_none());
7087 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7089 _ => panic!("Unexpected event"),
7093 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7095 check_added_monitors!(nodes[1], 0);
7096 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7097 expect_pending_htlcs_forwardable!(nodes[1]);
7098 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7099 assert_eq!(events_4.len(), 1);
7101 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7103 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, .. } } => {
7104 assert!(update_add_htlcs.is_empty());
7105 assert!(update_fulfill_htlcs.is_empty());
7106 assert_eq!(update_fail_htlcs.len(), 1);
7107 assert!(update_fail_malformed_htlcs.is_empty());
7108 assert!(update_fee.is_none());
7110 _ => panic!("Unexpected event"),
7113 check_added_monitors!(nodes[1], 1);
7116 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7117 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7118 // 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
7119 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7121 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7122 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7126 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7128 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7130 // We route 2 dust-HTLCs between A and B
7131 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7132 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7133 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7135 // Cache one local commitment tx as previous
7136 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7138 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7139 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7140 check_added_monitors!(nodes[1], 0);
7141 expect_pending_htlcs_forwardable!(nodes[1]);
7142 check_added_monitors!(nodes[1], 1);
7144 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7145 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7146 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7147 check_added_monitors!(nodes[0], 1);
7149 // Cache one local commitment tx as lastest
7150 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7152 let events = nodes[0].node.get_and_clear_pending_msg_events();
7154 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7155 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7157 _ => panic!("Unexpected event"),
7160 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7161 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7163 _ => panic!("Unexpected event"),
7166 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7167 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7168 if announce_latest {
7169 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7171 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7174 check_closed_broadcast!(nodes[0], true);
7175 check_added_monitors!(nodes[0], 1);
7176 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7178 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7179 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7180 let events = nodes[0].node.get_and_clear_pending_events();
7181 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7182 assert_eq!(events.len(), 2);
7183 let mut first_failed = false;
7184 for event in events {
7186 Event::PaymentPathFailed { payment_hash, .. } => {
7187 if payment_hash == payment_hash_1 {
7188 assert!(!first_failed);
7189 first_failed = true;
7191 assert_eq!(payment_hash, payment_hash_2);
7194 _ => panic!("Unexpected event"),
7200 fn test_failure_delay_dust_htlc_local_commitment() {
7201 do_test_failure_delay_dust_htlc_local_commitment(true);
7202 do_test_failure_delay_dust_htlc_local_commitment(false);
7205 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7206 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7207 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7208 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7209 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7210 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7211 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7213 let chanmon_cfgs = create_chanmon_cfgs(3);
7214 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7215 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7216 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7217 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7219 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7221 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7222 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7224 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7225 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7227 // We revoked bs_commitment_tx
7229 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7230 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7233 let mut timeout_tx = Vec::new();
7235 // We fail dust-HTLC 1 by broadcast of local commitment tx
7236 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7237 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7238 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7239 expect_payment_failed!(nodes[0], dust_hash, true);
7241 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7242 check_closed_broadcast!(nodes[0], true);
7243 check_added_monitors!(nodes[0], 1);
7244 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7245 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7246 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7247 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7248 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7249 mine_transaction(&nodes[0], &timeout_tx[0]);
7250 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7251 expect_payment_failed!(nodes[0], non_dust_hash, true);
7253 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7254 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7255 check_closed_broadcast!(nodes[0], true);
7256 check_added_monitors!(nodes[0], 1);
7257 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7258 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7259 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7260 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7262 expect_payment_failed!(nodes[0], dust_hash, true);
7263 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7264 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7265 mine_transaction(&nodes[0], &timeout_tx[0]);
7266 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7267 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7268 expect_payment_failed!(nodes[0], non_dust_hash, true);
7270 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7272 let events = nodes[0].node.get_and_clear_pending_events();
7273 assert_eq!(events.len(), 2);
7276 Event::PaymentPathFailed { payment_hash, .. } => {
7277 if payment_hash == dust_hash { first = true; }
7278 else { first = false; }
7280 _ => panic!("Unexpected event"),
7283 Event::PaymentPathFailed { payment_hash, .. } => {
7284 if first { assert_eq!(payment_hash, non_dust_hash); }
7285 else { assert_eq!(payment_hash, dust_hash); }
7287 _ => panic!("Unexpected event"),
7294 fn test_sweep_outbound_htlc_failure_update() {
7295 do_test_sweep_outbound_htlc_failure_update(false, true);
7296 do_test_sweep_outbound_htlc_failure_update(false, false);
7297 do_test_sweep_outbound_htlc_failure_update(true, false);
7301 fn test_user_configurable_csv_delay() {
7302 // We test our channel constructors yield errors when we pass them absurd csv delay
7304 let mut low_our_to_self_config = UserConfig::default();
7305 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7306 let mut high_their_to_self_config = UserConfig::default();
7307 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7308 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7309 let chanmon_cfgs = create_chanmon_cfgs(2);
7310 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7311 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7312 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7314 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7315 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7316 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7317 &low_our_to_self_config, 0, 42)
7320 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())); },
7321 _ => panic!("Unexpected event"),
7323 } else { assert!(false) }
7325 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7326 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7327 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7328 open_channel.to_self_delay = 200;
7329 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7330 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7331 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7334 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())); },
7335 _ => panic!("Unexpected event"),
7337 } else { assert!(false); }
7339 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7340 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7341 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7342 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7343 accept_channel.to_self_delay = 200;
7344 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7346 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7348 &ErrorAction::SendErrorMessage { ref msg } => {
7349 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()));
7350 reason_msg = msg.data.clone();
7354 } else { panic!(); }
7355 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7357 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7358 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7359 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7360 open_channel.to_self_delay = 200;
7361 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7362 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7363 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7366 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())); },
7367 _ => panic!("Unexpected event"),
7369 } else { assert!(false); }
7373 fn test_data_loss_protect() {
7374 // We want to be sure that :
7375 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7376 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7377 // * we close channel in case of detecting other being fallen behind
7378 // * we are able to claim our own outputs thanks to to_remote being static
7379 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7385 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7386 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7387 // during signing due to revoked tx
7388 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7389 let keys_manager = &chanmon_cfgs[0].keys_manager;
7392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7394 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7396 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7398 // Cache node A state before any channel update
7399 let previous_node_state = nodes[0].node.encode();
7400 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7401 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7403 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7404 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7406 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7407 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7409 // Restore node A from previous state
7410 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7411 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7412 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7413 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7414 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7415 persister = test_utils::TestPersister::new();
7416 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7418 let mut channel_monitors = HashMap::new();
7419 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7420 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7421 keys_manager: keys_manager,
7422 fee_estimator: &fee_estimator,
7423 chain_monitor: &monitor,
7425 tx_broadcaster: &tx_broadcaster,
7426 default_config: UserConfig::default(),
7430 nodes[0].node = &node_state_0;
7431 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7432 nodes[0].chain_monitor = &monitor;
7433 nodes[0].chain_source = &chain_source;
7435 check_added_monitors!(nodes[0], 1);
7437 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7438 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7440 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7442 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7443 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7444 check_added_monitors!(nodes[0], 1);
7447 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7448 assert_eq!(node_txn.len(), 0);
7451 let mut reestablish_1 = Vec::with_capacity(1);
7452 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7453 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7454 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7455 reestablish_1.push(msg.clone());
7456 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7457 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7459 &ErrorAction::SendErrorMessage { ref msg } => {
7460 assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7462 _ => panic!("Unexpected event!"),
7465 panic!("Unexpected event")
7469 // Check we close channel detecting A is fallen-behind
7470 // Check that we sent the warning message when we detected that A has fallen behind,
7471 // and give the possibility for A to recover from the warning.
7472 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7473 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7474 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7476 // Check A is able to claim to_remote output
7477 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7478 // The node B should not broadcast the transaction to force close the channel!
7479 assert!(node_txn.is_empty());
7480 // B should now detect that there is something wrong and should force close the channel.
7481 let exp_err = "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can\'t do any automated broadcasting";
7482 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7484 // after the warning message sent by B, we should not able to
7485 // use the channel, or reconnect with success to the channel.
7486 assert!(nodes[0].node.list_usable_channels().is_empty());
7487 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7488 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7489 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7491 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7492 let mut err_msgs_0 = Vec::with_capacity(1);
7493 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7494 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7496 &ErrorAction::SendErrorMessage { ref msg } => {
7497 assert_eq!(msg.data, "Failed to find corresponding channel");
7498 err_msgs_0.push(msg.clone());
7500 _ => panic!("Unexpected event!"),
7503 panic!("Unexpected event!");
7506 assert_eq!(err_msgs_0.len(), 1);
7507 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7508 assert!(nodes[1].node.list_usable_channels().is_empty());
7509 check_added_monitors!(nodes[1], 1);
7510 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7511 check_closed_broadcast!(nodes[1], false);
7515 fn test_check_htlc_underpaying() {
7516 // Send payment through A -> B but A is maliciously
7517 // sending a probe payment (i.e less than expected value0
7518 // to B, B should refuse payment.
7520 let chanmon_cfgs = create_chanmon_cfgs(2);
7521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7523 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7525 // Create some initial channels
7526 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7528 let scorer = test_utils::TestScorer::with_penalty(0);
7529 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7530 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7531 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();
7532 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7533 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7534 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7535 check_added_monitors!(nodes[0], 1);
7537 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7538 assert_eq!(events.len(), 1);
7539 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7540 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7541 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7543 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7544 // and then will wait a second random delay before failing the HTLC back:
7545 expect_pending_htlcs_forwardable!(nodes[1]);
7546 expect_pending_htlcs_forwardable!(nodes[1]);
7548 // Node 3 is expecting payment of 100_000 but received 10_000,
7549 // it should fail htlc like we didn't know the preimage.
7550 nodes[1].node.process_pending_htlc_forwards();
7552 let events = nodes[1].node.get_and_clear_pending_msg_events();
7553 assert_eq!(events.len(), 1);
7554 let (update_fail_htlc, commitment_signed) = match events[0] {
7555 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 } } => {
7556 assert!(update_add_htlcs.is_empty());
7557 assert!(update_fulfill_htlcs.is_empty());
7558 assert_eq!(update_fail_htlcs.len(), 1);
7559 assert!(update_fail_malformed_htlcs.is_empty());
7560 assert!(update_fee.is_none());
7561 (update_fail_htlcs[0].clone(), commitment_signed)
7563 _ => panic!("Unexpected event"),
7565 check_added_monitors!(nodes[1], 1);
7567 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7568 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7570 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7571 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7572 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7573 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7577 fn test_announce_disable_channels() {
7578 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7579 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7581 let chanmon_cfgs = create_chanmon_cfgs(2);
7582 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7583 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7584 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7586 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7587 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7588 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7591 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7592 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7594 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7595 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7596 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7597 assert_eq!(msg_events.len(), 3);
7598 let mut chans_disabled = HashMap::new();
7599 for e in msg_events {
7601 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7602 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7603 // Check that each channel gets updated exactly once
7604 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7605 panic!("Generated ChannelUpdate for wrong chan!");
7608 _ => panic!("Unexpected event"),
7612 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7613 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7614 assert_eq!(reestablish_1.len(), 3);
7615 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7616 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7617 assert_eq!(reestablish_2.len(), 3);
7619 // Reestablish chan_1
7620 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7621 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7622 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7623 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7624 // Reestablish chan_2
7625 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7626 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7627 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7628 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7629 // Reestablish chan_3
7630 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7631 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7632 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7633 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7635 nodes[0].node.timer_tick_occurred();
7636 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7637 nodes[0].node.timer_tick_occurred();
7638 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7639 assert_eq!(msg_events.len(), 3);
7640 for e in msg_events {
7642 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7643 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7644 match chans_disabled.remove(&msg.contents.short_channel_id) {
7645 // Each update should have a higher timestamp than the previous one, replacing
7647 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7648 None => panic!("Generated ChannelUpdate for wrong chan!"),
7651 _ => panic!("Unexpected event"),
7654 // Check that each channel gets updated exactly once
7655 assert!(chans_disabled.is_empty());
7659 fn test_bump_penalty_txn_on_revoked_commitment() {
7660 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7661 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7663 let chanmon_cfgs = create_chanmon_cfgs(2);
7664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7666 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7668 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7670 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7671 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7672 .with_features(InvoiceFeatures::known());
7673 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7674 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7676 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7677 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7678 assert_eq!(revoked_txn[0].output.len(), 4);
7679 assert_eq!(revoked_txn[0].input.len(), 1);
7680 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7681 let revoked_txid = revoked_txn[0].txid();
7683 let mut penalty_sum = 0;
7684 for outp in revoked_txn[0].output.iter() {
7685 if outp.script_pubkey.is_v0_p2wsh() {
7686 penalty_sum += outp.value;
7690 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7691 let header_114 = connect_blocks(&nodes[1], 14);
7693 // Actually revoke tx by claiming a HTLC
7694 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7695 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7696 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7697 check_added_monitors!(nodes[1], 1);
7699 // One or more justice tx should have been broadcast, check it
7703 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7704 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7705 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7706 assert_eq!(node_txn[0].output.len(), 1);
7707 check_spends!(node_txn[0], revoked_txn[0]);
7708 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7709 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7710 penalty_1 = node_txn[0].txid();
7714 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7715 connect_blocks(&nodes[1], 15);
7716 let mut penalty_2 = penalty_1;
7717 let mut feerate_2 = 0;
7719 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7720 assert_eq!(node_txn.len(), 1);
7721 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7722 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7723 assert_eq!(node_txn[0].output.len(), 1);
7724 check_spends!(node_txn[0], revoked_txn[0]);
7725 penalty_2 = node_txn[0].txid();
7726 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7727 assert_ne!(penalty_2, penalty_1);
7728 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7729 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7730 // Verify 25% bump heuristic
7731 assert!(feerate_2 * 100 >= feerate_1 * 125);
7735 assert_ne!(feerate_2, 0);
7737 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7738 connect_blocks(&nodes[1], 1);
7740 let mut feerate_3 = 0;
7742 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7743 assert_eq!(node_txn.len(), 1);
7744 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7745 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7746 assert_eq!(node_txn[0].output.len(), 1);
7747 check_spends!(node_txn[0], revoked_txn[0]);
7748 penalty_3 = node_txn[0].txid();
7749 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7750 assert_ne!(penalty_3, penalty_2);
7751 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7752 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7753 // Verify 25% bump heuristic
7754 assert!(feerate_3 * 100 >= feerate_2 * 125);
7758 assert_ne!(feerate_3, 0);
7760 nodes[1].node.get_and_clear_pending_events();
7761 nodes[1].node.get_and_clear_pending_msg_events();
7765 fn test_bump_penalty_txn_on_revoked_htlcs() {
7766 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7767 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7769 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7770 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7773 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7775 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7776 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7777 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7778 let scorer = test_utils::TestScorer::with_penalty(0);
7779 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7780 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7781 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7782 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7783 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7784 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7785 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7786 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7788 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7789 assert_eq!(revoked_local_txn[0].input.len(), 1);
7790 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7792 // Revoke local commitment tx
7793 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7795 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7796 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7797 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7798 check_closed_broadcast!(nodes[1], true);
7799 check_added_monitors!(nodes[1], 1);
7800 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7801 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7803 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7804 assert_eq!(revoked_htlc_txn.len(), 3);
7805 check_spends!(revoked_htlc_txn[1], chan.3);
7807 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7808 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7809 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7811 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7812 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7813 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7814 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7816 // Broadcast set of revoked txn on A
7817 let hash_128 = connect_blocks(&nodes[0], 40);
7818 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7819 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7820 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7821 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7822 let events = nodes[0].node.get_and_clear_pending_events();
7823 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7825 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7826 _ => panic!("Unexpected event"),
7832 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7833 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7834 // Verify claim tx are spending revoked HTLC txn
7836 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7837 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7838 // which are included in the same block (they are broadcasted because we scan the
7839 // transactions linearly and generate claims as we go, they likely should be removed in the
7841 assert_eq!(node_txn[0].input.len(), 1);
7842 check_spends!(node_txn[0], revoked_local_txn[0]);
7843 assert_eq!(node_txn[1].input.len(), 1);
7844 check_spends!(node_txn[1], revoked_local_txn[0]);
7845 assert_eq!(node_txn[2].input.len(), 1);
7846 check_spends!(node_txn[2], revoked_local_txn[0]);
7848 // Each of the three justice transactions claim a separate (single) output of the three
7849 // available, which we check here:
7850 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7851 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7852 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7854 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7855 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7857 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7858 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7859 // a remote commitment tx has already been confirmed).
7860 check_spends!(node_txn[3], chan.3);
7862 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7863 // output, checked above).
7864 assert_eq!(node_txn[4].input.len(), 2);
7865 assert_eq!(node_txn[4].output.len(), 1);
7866 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7868 first = node_txn[4].txid();
7869 // Store both feerates for later comparison
7870 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7871 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7872 penalty_txn = vec![node_txn[2].clone()];
7876 // Connect one more block to see if bumped penalty are issued for HTLC txn
7877 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7878 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7879 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7880 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7882 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7883 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7885 check_spends!(node_txn[0], revoked_local_txn[0]);
7886 check_spends!(node_txn[1], revoked_local_txn[0]);
7887 // Note that these are both bogus - they spend outputs already claimed in block 129:
7888 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7889 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7891 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7892 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7898 // Few more blocks to confirm penalty txn
7899 connect_blocks(&nodes[0], 4);
7900 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7901 let header_144 = connect_blocks(&nodes[0], 9);
7903 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7904 assert_eq!(node_txn.len(), 1);
7906 assert_eq!(node_txn[0].input.len(), 2);
7907 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7908 // Verify bumped tx is different and 25% bump heuristic
7909 assert_ne!(first, node_txn[0].txid());
7910 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7911 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7912 assert!(feerate_2 * 100 > feerate_1 * 125);
7913 let txn = vec![node_txn[0].clone()];
7917 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7918 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7919 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7920 connect_blocks(&nodes[0], 20);
7922 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7923 // We verify than no new transaction has been broadcast because previously
7924 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7925 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7926 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7927 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7928 // up bumped justice generation.
7929 assert_eq!(node_txn.len(), 0);
7932 check_closed_broadcast!(nodes[0], true);
7933 check_added_monitors!(nodes[0], 1);
7937 fn test_bump_penalty_txn_on_remote_commitment() {
7938 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7939 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7942 // Provide preimage for one
7943 // Check aggregation
7945 let chanmon_cfgs = create_chanmon_cfgs(2);
7946 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7947 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7948 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7950 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7951 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7952 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7954 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7955 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7956 assert_eq!(remote_txn[0].output.len(), 4);
7957 assert_eq!(remote_txn[0].input.len(), 1);
7958 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7960 // Claim a HTLC without revocation (provide B monitor with preimage)
7961 nodes[1].node.claim_funds(payment_preimage);
7962 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7963 mine_transaction(&nodes[1], &remote_txn[0]);
7964 check_added_monitors!(nodes[1], 2);
7965 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7967 // One or more claim tx should have been broadcast, check it
7971 let feerate_timeout;
7972 let feerate_preimage;
7974 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7975 // 9 transactions including:
7976 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7977 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7978 // 2 * HTLC-Success (one RBF bump we'll check later)
7980 assert_eq!(node_txn.len(), 8);
7981 assert_eq!(node_txn[0].input.len(), 1);
7982 assert_eq!(node_txn[6].input.len(), 1);
7983 check_spends!(node_txn[0], remote_txn[0]);
7984 check_spends!(node_txn[6], remote_txn[0]);
7985 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7986 preimage_bump = node_txn[3].clone();
7988 check_spends!(node_txn[1], chan.3);
7989 check_spends!(node_txn[2], node_txn[1]);
7990 assert_eq!(node_txn[1], node_txn[4]);
7991 assert_eq!(node_txn[2], node_txn[5]);
7993 timeout = node_txn[6].txid();
7994 let index = node_txn[6].input[0].previous_output.vout;
7995 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7996 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
7998 preimage = node_txn[0].txid();
7999 let index = node_txn[0].input[0].previous_output.vout;
8000 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8001 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8005 assert_ne!(feerate_timeout, 0);
8006 assert_ne!(feerate_preimage, 0);
8008 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8009 connect_blocks(&nodes[1], 15);
8011 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8012 assert_eq!(node_txn.len(), 1);
8013 assert_eq!(node_txn[0].input.len(), 1);
8014 assert_eq!(preimage_bump.input.len(), 1);
8015 check_spends!(node_txn[0], remote_txn[0]);
8016 check_spends!(preimage_bump, remote_txn[0]);
8018 let index = preimage_bump.input[0].previous_output.vout;
8019 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8020 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8021 assert!(new_feerate * 100 > feerate_timeout * 125);
8022 assert_ne!(timeout, preimage_bump.txid());
8024 let index = node_txn[0].input[0].previous_output.vout;
8025 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8026 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8027 assert!(new_feerate * 100 > feerate_preimage * 125);
8028 assert_ne!(preimage, node_txn[0].txid());
8033 nodes[1].node.get_and_clear_pending_events();
8034 nodes[1].node.get_and_clear_pending_msg_events();
8038 fn test_counterparty_raa_skip_no_crash() {
8039 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8040 // commitment transaction, we would have happily carried on and provided them the next
8041 // commitment transaction based on one RAA forward. This would probably eventually have led to
8042 // channel closure, but it would not have resulted in funds loss. Still, our
8043 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8044 // check simply that the channel is closed in response to such an RAA, but don't check whether
8045 // we decide to punish our counterparty for revoking their funds (as we don't currently
8047 let chanmon_cfgs = create_chanmon_cfgs(2);
8048 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8049 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8050 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8051 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8053 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8054 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8056 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8058 // Make signer believe we got a counterparty signature, so that it allows the revocation
8059 keys.get_enforcement_state().last_holder_commitment -= 1;
8060 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8062 // Must revoke without gaps
8063 keys.get_enforcement_state().last_holder_commitment -= 1;
8064 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8066 keys.get_enforcement_state().last_holder_commitment -= 1;
8067 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8068 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8070 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8071 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8072 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8073 check_added_monitors!(nodes[1], 1);
8074 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8078 fn test_bump_txn_sanitize_tracking_maps() {
8079 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8080 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8082 let chanmon_cfgs = create_chanmon_cfgs(2);
8083 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8084 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8085 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8087 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8088 // Lock HTLC in both directions
8089 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8090 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8092 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8093 assert_eq!(revoked_local_txn[0].input.len(), 1);
8094 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8096 // Revoke local commitment tx
8097 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8099 // Broadcast set of revoked txn on A
8100 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8101 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8102 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8104 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8105 check_closed_broadcast!(nodes[0], true);
8106 check_added_monitors!(nodes[0], 1);
8107 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8109 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8110 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8111 check_spends!(node_txn[0], revoked_local_txn[0]);
8112 check_spends!(node_txn[1], revoked_local_txn[0]);
8113 check_spends!(node_txn[2], revoked_local_txn[0]);
8114 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8118 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8119 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8120 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8122 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8123 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8124 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8129 fn test_pending_claimed_htlc_no_balance_underflow() {
8130 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8131 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8132 let chanmon_cfgs = create_chanmon_cfgs(2);
8133 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8134 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8135 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8136 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8138 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8139 nodes[1].node.claim_funds(payment_preimage);
8140 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8141 check_added_monitors!(nodes[1], 1);
8142 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8144 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8145 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8146 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8147 check_added_monitors!(nodes[0], 1);
8148 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8150 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8151 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8152 // can get our balance.
8154 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8155 // the public key of the only hop. This works around ChannelDetails not showing the
8156 // almost-claimed HTLC as available balance.
8157 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8158 route.payment_params = None; // This is all wrong, but unnecessary
8159 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8160 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8161 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8163 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8167 fn test_channel_conf_timeout() {
8168 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8169 // confirm within 2016 blocks, as recommended by BOLT 2.
8170 let chanmon_cfgs = create_chanmon_cfgs(2);
8171 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8172 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8173 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8175 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8177 // The outbound node should wait forever for confirmation:
8178 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8179 // copied here instead of directly referencing the constant.
8180 connect_blocks(&nodes[0], 2016);
8181 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8183 // The inbound node should fail the channel after exactly 2016 blocks
8184 connect_blocks(&nodes[1], 2015);
8185 check_added_monitors!(nodes[1], 0);
8186 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8188 connect_blocks(&nodes[1], 1);
8189 check_added_monitors!(nodes[1], 1);
8190 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8191 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8192 assert_eq!(close_ev.len(), 1);
8194 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8195 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8196 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8198 _ => panic!("Unexpected event"),
8203 fn test_override_channel_config() {
8204 let chanmon_cfgs = create_chanmon_cfgs(2);
8205 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8206 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8207 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8209 // Node0 initiates a channel to node1 using the override config.
8210 let mut override_config = UserConfig::default();
8211 override_config.own_channel_config.our_to_self_delay = 200;
8213 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8215 // Assert the channel created by node0 is using the override config.
8216 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8217 assert_eq!(res.channel_flags, 0);
8218 assert_eq!(res.to_self_delay, 200);
8222 fn test_override_0msat_htlc_minimum() {
8223 let mut zero_config = UserConfig::default();
8224 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8225 let chanmon_cfgs = create_chanmon_cfgs(2);
8226 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8227 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8228 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8230 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8231 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8232 assert_eq!(res.htlc_minimum_msat, 1);
8234 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8235 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8236 assert_eq!(res.htlc_minimum_msat, 1);
8240 fn test_channel_update_has_correct_htlc_maximum_msat() {
8241 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8242 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8243 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8244 // 90% of the `channel_value`.
8245 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8247 let mut config_30_percent = UserConfig::default();
8248 config_30_percent.channel_options.announced_channel = true;
8249 config_30_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8250 let mut config_50_percent = UserConfig::default();
8251 config_50_percent.channel_options.announced_channel = true;
8252 config_50_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8253 let mut config_95_percent = UserConfig::default();
8254 config_95_percent.channel_options.announced_channel = true;
8255 config_95_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8256 let mut config_100_percent = UserConfig::default();
8257 config_100_percent.channel_options.announced_channel = true;
8258 config_100_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8260 let chanmon_cfgs = create_chanmon_cfgs(4);
8261 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8262 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)]);
8263 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8265 let channel_value_satoshis = 100000;
8266 let channel_value_msat = channel_value_satoshis * 1000;
8267 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8268 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8269 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8271 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8272 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8274 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8275 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8276 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8277 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8278 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8279 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8281 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8282 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8284 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8285 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8286 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8288 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8292 fn test_manually_accept_inbound_channel_request() {
8293 let mut manually_accept_conf = UserConfig::default();
8294 manually_accept_conf.manually_accept_inbound_channels = true;
8295 let chanmon_cfgs = create_chanmon_cfgs(2);
8296 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8297 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8298 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8300 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8301 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8303 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8305 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8306 // accepting the inbound channel request.
8307 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8309 let events = nodes[1].node.get_and_clear_pending_events();
8311 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8312 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8314 _ => panic!("Unexpected event"),
8317 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8318 assert_eq!(accept_msg_ev.len(), 1);
8320 match accept_msg_ev[0] {
8321 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8322 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8324 _ => panic!("Unexpected event"),
8327 nodes[1].node.force_close_channel(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8329 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8330 assert_eq!(close_msg_ev.len(), 1);
8332 let events = nodes[1].node.get_and_clear_pending_events();
8334 Event::ChannelClosed { user_channel_id, .. } => {
8335 assert_eq!(user_channel_id, 23);
8337 _ => panic!("Unexpected event"),
8342 fn test_manually_reject_inbound_channel_request() {
8343 let mut manually_accept_conf = UserConfig::default();
8344 manually_accept_conf.manually_accept_inbound_channels = true;
8345 let chanmon_cfgs = create_chanmon_cfgs(2);
8346 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8347 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8348 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8350 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8351 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8353 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8355 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8356 // rejecting the inbound channel request.
8357 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8359 let events = nodes[1].node.get_and_clear_pending_events();
8361 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8362 nodes[1].node.force_close_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8364 _ => panic!("Unexpected event"),
8367 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8368 assert_eq!(close_msg_ev.len(), 1);
8370 match close_msg_ev[0] {
8371 MessageSendEvent::HandleError { ref node_id, .. } => {
8372 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8374 _ => panic!("Unexpected event"),
8376 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8380 fn test_reject_funding_before_inbound_channel_accepted() {
8381 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8382 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8383 // the node operator before the counterparty sends a `FundingCreated` message. If a
8384 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8385 // and the channel should be closed.
8386 let mut manually_accept_conf = UserConfig::default();
8387 manually_accept_conf.manually_accept_inbound_channels = true;
8388 let chanmon_cfgs = create_chanmon_cfgs(2);
8389 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8390 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8391 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8393 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8394 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8395 let temp_channel_id = res.temporary_channel_id;
8397 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8399 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8400 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8402 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8403 nodes[1].node.get_and_clear_pending_events();
8405 // Get the `AcceptChannel` message of `nodes[1]` without calling
8406 // `ChannelManager::accept_inbound_channel`, which generates a
8407 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8408 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8409 // succeed when `nodes[0]` is passed to it.
8412 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8413 let accept_chan_msg = channel.get_accept_channel_message();
8414 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8417 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8419 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8420 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8422 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8423 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8425 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8426 assert_eq!(close_msg_ev.len(), 1);
8428 let expected_err = "FundingCreated message received before the channel was accepted";
8429 match close_msg_ev[0] {
8430 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8431 assert_eq!(msg.channel_id, temp_channel_id);
8432 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8433 assert_eq!(msg.data, expected_err);
8435 _ => panic!("Unexpected event"),
8438 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8442 fn test_can_not_accept_inbound_channel_twice() {
8443 let mut manually_accept_conf = UserConfig::default();
8444 manually_accept_conf.manually_accept_inbound_channels = true;
8445 let chanmon_cfgs = create_chanmon_cfgs(2);
8446 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8447 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8448 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8450 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8451 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8453 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8455 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8456 // accepting the inbound channel request.
8457 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8459 let events = nodes[1].node.get_and_clear_pending_events();
8461 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8462 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8463 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8465 Err(APIError::APIMisuseError { err }) => {
8466 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8468 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8469 Err(_) => panic!("Unexpected Error"),
8472 _ => panic!("Unexpected event"),
8475 // Ensure that the channel wasn't closed after attempting to accept it twice.
8476 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8477 assert_eq!(accept_msg_ev.len(), 1);
8479 match accept_msg_ev[0] {
8480 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8481 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8483 _ => panic!("Unexpected event"),
8488 fn test_can_not_accept_unknown_inbound_channel() {
8489 let chanmon_cfg = create_chanmon_cfgs(2);
8490 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8491 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8492 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8494 let unknown_channel_id = [0; 32];
8495 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8497 Err(APIError::ChannelUnavailable { err }) => {
8498 assert_eq!(err, "Can't accept a channel that doesn't exist");
8500 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8501 Err(_) => panic!("Unexpected Error"),
8506 fn test_simple_mpp() {
8507 // Simple test of sending a multi-path payment.
8508 let chanmon_cfgs = create_chanmon_cfgs(4);
8509 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8510 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8511 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8513 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8514 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8515 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8516 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8518 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8519 let path = route.paths[0].clone();
8520 route.paths.push(path);
8521 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8522 route.paths[0][0].short_channel_id = chan_1_id;
8523 route.paths[0][1].short_channel_id = chan_3_id;
8524 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8525 route.paths[1][0].short_channel_id = chan_2_id;
8526 route.paths[1][1].short_channel_id = chan_4_id;
8527 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8528 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8532 fn test_preimage_storage() {
8533 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8534 let chanmon_cfgs = create_chanmon_cfgs(2);
8535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8537 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8539 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8542 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8543 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8544 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8545 check_added_monitors!(nodes[0], 1);
8546 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8547 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8548 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8549 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8551 // Note that after leaving the above scope we have no knowledge of any arguments or return
8552 // values from previous calls.
8553 expect_pending_htlcs_forwardable!(nodes[1]);
8554 let events = nodes[1].node.get_and_clear_pending_events();
8555 assert_eq!(events.len(), 1);
8557 Event::PaymentReceived { ref purpose, .. } => {
8559 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8560 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8562 _ => panic!("expected PaymentPurpose::InvoicePayment")
8565 _ => panic!("Unexpected event"),
8570 #[allow(deprecated)]
8571 fn test_secret_timeout() {
8572 // Simple test of payment secret storage time outs. After
8573 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8574 let chanmon_cfgs = create_chanmon_cfgs(2);
8575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8579 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8581 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8583 // We should fail to register the same payment hash twice, at least until we've connected a
8584 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8585 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8586 assert_eq!(err, "Duplicate payment hash");
8587 } else { panic!(); }
8589 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8591 header: BlockHeader {
8593 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8594 merkle_root: Default::default(),
8595 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8599 connect_block(&nodes[1], &block);
8600 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8601 assert_eq!(err, "Duplicate payment hash");
8602 } else { panic!(); }
8604 // If we then connect the second block, we should be able to register the same payment hash
8605 // again (this time getting a new payment secret).
8606 block.header.prev_blockhash = block.header.block_hash();
8607 block.header.time += 1;
8608 connect_block(&nodes[1], &block);
8609 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8610 assert_ne!(payment_secret_1, our_payment_secret);
8613 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8614 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8615 check_added_monitors!(nodes[0], 1);
8616 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8617 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8618 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8619 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8621 // Note that after leaving the above scope we have no knowledge of any arguments or return
8622 // values from previous calls.
8623 expect_pending_htlcs_forwardable!(nodes[1]);
8624 let events = nodes[1].node.get_and_clear_pending_events();
8625 assert_eq!(events.len(), 1);
8627 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8628 assert!(payment_preimage.is_none());
8629 assert_eq!(payment_secret, our_payment_secret);
8630 // We don't actually have the payment preimage with which to claim this payment!
8632 _ => panic!("Unexpected event"),
8637 fn test_bad_secret_hash() {
8638 // Simple test of unregistered payment hash/invalid payment secret handling
8639 let chanmon_cfgs = create_chanmon_cfgs(2);
8640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8642 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8644 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8646 let random_payment_hash = PaymentHash([42; 32]);
8647 let random_payment_secret = PaymentSecret([43; 32]);
8648 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8649 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8651 // All the below cases should end up being handled exactly identically, so we macro the
8652 // resulting events.
8653 macro_rules! handle_unknown_invalid_payment_data {
8655 check_added_monitors!(nodes[0], 1);
8656 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8657 let payment_event = SendEvent::from_event(events.pop().unwrap());
8658 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8659 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8661 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8662 // again to process the pending backwards-failure of the HTLC
8663 expect_pending_htlcs_forwardable!(nodes[1]);
8664 expect_pending_htlcs_forwardable!(nodes[1]);
8665 check_added_monitors!(nodes[1], 1);
8667 // We should fail the payment back
8668 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8669 match events.pop().unwrap() {
8670 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8671 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8672 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8674 _ => panic!("Unexpected event"),
8679 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8680 // Error data is the HTLC value (100,000) and current block height
8681 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8683 // Send a payment with the right payment hash but the wrong payment secret
8684 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8685 handle_unknown_invalid_payment_data!();
8686 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8688 // Send a payment with a random payment hash, but the right payment secret
8689 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8690 handle_unknown_invalid_payment_data!();
8691 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8693 // Send a payment with a random payment hash and random payment secret
8694 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8695 handle_unknown_invalid_payment_data!();
8696 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8700 fn test_update_err_monitor_lockdown() {
8701 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8702 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8703 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8705 // This scenario may happen in a watchtower setup, where watchtower process a block height
8706 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8707 // commitment at same time.
8709 let chanmon_cfgs = create_chanmon_cfgs(2);
8710 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8711 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8712 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8714 // Create some initial channel
8715 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8716 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8718 // Rebalance the network to generate htlc in the two directions
8719 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8721 // Route a HTLC from node 0 to node 1 (but don't settle)
8722 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8724 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8725 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8726 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8727 let persister = test_utils::TestPersister::new();
8729 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8730 let mut w = test_utils::TestVecWriter(Vec::new());
8731 monitor.write(&mut w).unwrap();
8732 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8733 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8734 assert!(new_monitor == *monitor);
8735 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);
8736 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8739 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8740 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8741 // transaction lock time requirements here.
8742 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8743 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8745 // Try to update ChannelMonitor
8746 nodes[1].node.claim_funds(preimage);
8747 check_added_monitors!(nodes[1], 1);
8748 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8750 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8751 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8752 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8753 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8754 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8755 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8756 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8757 } else { assert!(false); }
8758 } else { assert!(false); };
8759 // Our local monitor is in-sync and hasn't processed yet timeout
8760 check_added_monitors!(nodes[0], 1);
8761 let events = nodes[0].node.get_and_clear_pending_events();
8762 assert_eq!(events.len(), 1);
8766 fn test_concurrent_monitor_claim() {
8767 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8768 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8769 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8770 // state N+1 confirms. Alice claims output from state N+1.
8772 let chanmon_cfgs = create_chanmon_cfgs(2);
8773 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8774 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8775 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8777 // Create some initial channel
8778 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8779 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8781 // Rebalance the network to generate htlc in the two directions
8782 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8784 // Route a HTLC from node 0 to node 1 (but don't settle)
8785 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8787 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8788 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8789 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8790 let persister = test_utils::TestPersister::new();
8791 let watchtower_alice = {
8792 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8793 let mut w = test_utils::TestVecWriter(Vec::new());
8794 monitor.write(&mut w).unwrap();
8795 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8796 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8797 assert!(new_monitor == *monitor);
8798 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);
8799 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8802 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8803 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8804 // transaction lock time requirements here.
8805 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8806 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8808 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8810 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8811 assert_eq!(txn.len(), 2);
8815 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8816 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8817 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8818 let persister = test_utils::TestPersister::new();
8819 let watchtower_bob = {
8820 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8821 let mut w = test_utils::TestVecWriter(Vec::new());
8822 monitor.write(&mut w).unwrap();
8823 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8824 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8825 assert!(new_monitor == *monitor);
8826 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);
8827 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8830 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8831 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8833 // Route another payment to generate another update with still previous HTLC pending
8834 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8836 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8838 check_added_monitors!(nodes[1], 1);
8840 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8841 assert_eq!(updates.update_add_htlcs.len(), 1);
8842 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8843 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8844 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8845 // Watchtower Alice should already have seen the block and reject the update
8846 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8847 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8848 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8849 } else { assert!(false); }
8850 } else { assert!(false); };
8851 // Our local monitor is in-sync and hasn't processed yet timeout
8852 check_added_monitors!(nodes[0], 1);
8854 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8855 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8856 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8858 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8861 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8862 assert_eq!(txn.len(), 2);
8863 bob_state_y = txn[0].clone();
8867 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8868 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8869 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);
8871 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8872 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8873 // the onchain detection of the HTLC output
8874 assert_eq!(htlc_txn.len(), 2);
8875 check_spends!(htlc_txn[0], bob_state_y);
8876 check_spends!(htlc_txn[1], bob_state_y);
8881 fn test_pre_lockin_no_chan_closed_update() {
8882 // Test that if a peer closes a channel in response to a funding_created message we don't
8883 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8886 // Doing so would imply a channel monitor update before the initial channel monitor
8887 // registration, violating our API guarantees.
8889 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8890 // then opening a second channel with the same funding output as the first (which is not
8891 // rejected because the first channel does not exist in the ChannelManager) and closing it
8892 // before receiving funding_signed.
8893 let chanmon_cfgs = create_chanmon_cfgs(2);
8894 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8895 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8896 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8898 // Create an initial channel
8899 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8900 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8901 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8902 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8903 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8905 // Move the first channel through the funding flow...
8906 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8908 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8909 check_added_monitors!(nodes[0], 0);
8911 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8912 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8913 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8914 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8915 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8919 fn test_htlc_no_detection() {
8920 // This test is a mutation to underscore the detection logic bug we had
8921 // before #653. HTLC value routed is above the remaining balance, thus
8922 // inverting HTLC and `to_remote` output. HTLC will come second and
8923 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8924 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8925 // outputs order detection for correct spending children filtring.
8927 let chanmon_cfgs = create_chanmon_cfgs(2);
8928 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8929 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8930 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8932 // Create some initial channels
8933 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8935 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8936 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8937 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8938 assert_eq!(local_txn[0].input.len(), 1);
8939 assert_eq!(local_txn[0].output.len(), 3);
8940 check_spends!(local_txn[0], chan_1.3);
8942 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8943 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8944 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8945 // We deliberately connect the local tx twice as this should provoke a failure calling
8946 // this test before #653 fix.
8947 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);
8948 check_closed_broadcast!(nodes[0], true);
8949 check_added_monitors!(nodes[0], 1);
8950 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8951 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8953 let htlc_timeout = {
8954 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8955 assert_eq!(node_txn[1].input.len(), 1);
8956 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8957 check_spends!(node_txn[1], local_txn[0]);
8961 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8962 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8963 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8964 expect_payment_failed!(nodes[0], our_payment_hash, true);
8967 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8968 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8969 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8970 // Carol, Alice would be the upstream node, and Carol the downstream.)
8972 // Steps of the test:
8973 // 1) Alice sends a HTLC to Carol through Bob.
8974 // 2) Carol doesn't settle the HTLC.
8975 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8976 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8977 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8978 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8979 // 5) Carol release the preimage to Bob off-chain.
8980 // 6) Bob claims the offered output on the broadcasted commitment.
8981 let chanmon_cfgs = create_chanmon_cfgs(3);
8982 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8983 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8984 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8986 // Create some initial channels
8987 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8988 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8990 // Steps (1) and (2):
8991 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8992 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8994 // Check that Alice's commitment transaction now contains an output for this HTLC.
8995 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8996 check_spends!(alice_txn[0], chan_ab.3);
8997 assert_eq!(alice_txn[0].output.len(), 2);
8998 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8999 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9000 assert_eq!(alice_txn.len(), 2);
9002 // Steps (3) and (4):
9003 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9004 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9005 let mut force_closing_node = 0; // Alice force-closes
9006 let mut counterparty_node = 1; // Bob if Alice force-closes
9009 if !broadcast_alice {
9010 force_closing_node = 1;
9011 counterparty_node = 0;
9013 nodes[force_closing_node].node.force_close_channel(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9014 check_closed_broadcast!(nodes[force_closing_node], true);
9015 check_added_monitors!(nodes[force_closing_node], 1);
9016 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9017 if go_onchain_before_fulfill {
9018 let txn_to_broadcast = match broadcast_alice {
9019 true => alice_txn.clone(),
9020 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9022 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9023 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9024 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9025 if broadcast_alice {
9026 check_closed_broadcast!(nodes[1], true);
9027 check_added_monitors!(nodes[1], 1);
9028 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9030 assert_eq!(bob_txn.len(), 1);
9031 check_spends!(bob_txn[0], chan_ab.3);
9035 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9036 // process of removing the HTLC from their commitment transactions.
9037 nodes[2].node.claim_funds(payment_preimage);
9038 check_added_monitors!(nodes[2], 1);
9039 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9041 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9042 assert!(carol_updates.update_add_htlcs.is_empty());
9043 assert!(carol_updates.update_fail_htlcs.is_empty());
9044 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9045 assert!(carol_updates.update_fee.is_none());
9046 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9048 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9049 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9050 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9051 if !go_onchain_before_fulfill && broadcast_alice {
9052 let events = nodes[1].node.get_and_clear_pending_msg_events();
9053 assert_eq!(events.len(), 1);
9055 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9056 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9058 _ => panic!("Unexpected event"),
9061 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9062 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9063 // Carol<->Bob's updated commitment transaction info.
9064 check_added_monitors!(nodes[1], 2);
9066 let events = nodes[1].node.get_and_clear_pending_msg_events();
9067 assert_eq!(events.len(), 2);
9068 let bob_revocation = match events[0] {
9069 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9070 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9073 _ => panic!("Unexpected event"),
9075 let bob_updates = match events[1] {
9076 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9077 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9080 _ => panic!("Unexpected event"),
9083 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9084 check_added_monitors!(nodes[2], 1);
9085 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9086 check_added_monitors!(nodes[2], 1);
9088 let events = nodes[2].node.get_and_clear_pending_msg_events();
9089 assert_eq!(events.len(), 1);
9090 let carol_revocation = match events[0] {
9091 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9092 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9095 _ => panic!("Unexpected event"),
9097 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9098 check_added_monitors!(nodes[1], 1);
9100 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9101 // here's where we put said channel's commitment tx on-chain.
9102 let mut txn_to_broadcast = alice_txn.clone();
9103 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9104 if !go_onchain_before_fulfill {
9105 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9106 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9107 // If Bob was the one to force-close, he will have already passed these checks earlier.
9108 if broadcast_alice {
9109 check_closed_broadcast!(nodes[1], true);
9110 check_added_monitors!(nodes[1], 1);
9111 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9113 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9114 if broadcast_alice {
9115 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9116 // new block being connected. The ChannelManager being notified triggers a monitor update,
9117 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9118 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9120 assert_eq!(bob_txn.len(), 3);
9121 check_spends!(bob_txn[1], chan_ab.3);
9123 assert_eq!(bob_txn.len(), 2);
9124 check_spends!(bob_txn[0], chan_ab.3);
9129 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9130 // broadcasted commitment transaction.
9132 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9133 if go_onchain_before_fulfill {
9134 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9135 assert_eq!(bob_txn.len(), 2);
9137 let script_weight = match broadcast_alice {
9138 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9139 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9141 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9142 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9143 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9144 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9145 if broadcast_alice && !go_onchain_before_fulfill {
9146 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9147 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9149 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9150 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9156 fn test_onchain_htlc_settlement_after_close() {
9157 do_test_onchain_htlc_settlement_after_close(true, true);
9158 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9159 do_test_onchain_htlc_settlement_after_close(true, false);
9160 do_test_onchain_htlc_settlement_after_close(false, false);
9164 fn test_duplicate_chan_id() {
9165 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9166 // already open we reject it and keep the old channel.
9168 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9169 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9170 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9171 // updating logic for the existing channel.
9172 let chanmon_cfgs = create_chanmon_cfgs(2);
9173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9177 // Create an initial channel
9178 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9179 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9180 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9181 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9183 // Try to create a second channel with the same temporary_channel_id as the first and check
9184 // that it is rejected.
9185 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9187 let events = nodes[1].node.get_and_clear_pending_msg_events();
9188 assert_eq!(events.len(), 1);
9190 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9191 // Technically, at this point, nodes[1] would be justified in thinking both the
9192 // first (valid) and second (invalid) channels are closed, given they both have
9193 // the same non-temporary channel_id. However, currently we do not, so we just
9194 // move forward with it.
9195 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9196 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9198 _ => panic!("Unexpected event"),
9202 // Move the first channel through the funding flow...
9203 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9205 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9206 check_added_monitors!(nodes[0], 0);
9208 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9209 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9211 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9212 assert_eq!(added_monitors.len(), 1);
9213 assert_eq!(added_monitors[0].0, funding_output);
9214 added_monitors.clear();
9216 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9218 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9219 let channel_id = funding_outpoint.to_channel_id();
9221 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9224 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9225 // Technically this is allowed by the spec, but we don't support it and there's little reason
9226 // to. Still, it shouldn't cause any other issues.
9227 open_chan_msg.temporary_channel_id = channel_id;
9228 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9230 let events = nodes[1].node.get_and_clear_pending_msg_events();
9231 assert_eq!(events.len(), 1);
9233 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9234 // Technically, at this point, nodes[1] would be justified in thinking both
9235 // channels are closed, but currently we do not, so we just move forward with it.
9236 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9237 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9239 _ => panic!("Unexpected event"),
9243 // Now try to create a second channel which has a duplicate funding output.
9244 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9245 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9246 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9247 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9248 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9250 let funding_created = {
9251 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9252 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9253 let logger = test_utils::TestLogger::new();
9254 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9256 check_added_monitors!(nodes[0], 0);
9257 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9258 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9259 // still needs to be cleared here.
9260 check_added_monitors!(nodes[1], 1);
9262 // ...still, nodes[1] will reject the duplicate channel.
9264 let events = nodes[1].node.get_and_clear_pending_msg_events();
9265 assert_eq!(events.len(), 1);
9267 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9268 // Technically, at this point, nodes[1] would be justified in thinking both
9269 // channels are closed, but currently we do not, so we just move forward with it.
9270 assert_eq!(msg.channel_id, channel_id);
9271 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9273 _ => panic!("Unexpected event"),
9277 // finally, finish creating the original channel and send a payment over it to make sure
9278 // everything is functional.
9279 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9281 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9282 assert_eq!(added_monitors.len(), 1);
9283 assert_eq!(added_monitors[0].0, funding_output);
9284 added_monitors.clear();
9287 let events_4 = nodes[0].node.get_and_clear_pending_events();
9288 assert_eq!(events_4.len(), 0);
9289 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9290 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9292 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9293 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9294 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9295 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9299 fn test_error_chans_closed() {
9300 // Test that we properly handle error messages, closing appropriate channels.
9302 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9303 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9304 // we can test various edge cases around it to ensure we don't regress.
9305 let chanmon_cfgs = create_chanmon_cfgs(3);
9306 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9307 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9308 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9310 // Create some initial channels
9311 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9312 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9313 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9315 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9316 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9317 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9319 // Closing a channel from a different peer has no effect
9320 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9321 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9323 // Closing one channel doesn't impact others
9324 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9325 check_added_monitors!(nodes[0], 1);
9326 check_closed_broadcast!(nodes[0], false);
9327 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9328 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9329 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9330 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);
9331 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);
9333 // A null channel ID should close all channels
9334 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9335 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9336 check_added_monitors!(nodes[0], 2);
9337 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9338 let events = nodes[0].node.get_and_clear_pending_msg_events();
9339 assert_eq!(events.len(), 2);
9341 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9342 assert_eq!(msg.contents.flags & 2, 2);
9344 _ => panic!("Unexpected event"),
9347 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9348 assert_eq!(msg.contents.flags & 2, 2);
9350 _ => panic!("Unexpected event"),
9352 // Note that at this point users of a standard PeerHandler will end up calling
9353 // peer_disconnected with no_connection_possible set to false, duplicating the
9354 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9355 // users with their own peer handling logic. We duplicate the call here, however.
9356 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9357 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9359 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9360 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9361 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9365 fn test_invalid_funding_tx() {
9366 // Test that we properly handle invalid funding transactions sent to us from a peer.
9368 // Previously, all other major lightning implementations had failed to properly sanitize
9369 // funding transactions from their counterparties, leading to a multi-implementation critical
9370 // security vulnerability (though we always sanitized properly, we've previously had
9371 // un-released crashes in the sanitization process).
9372 let chanmon_cfgs = create_chanmon_cfgs(2);
9373 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9374 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9375 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9377 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9378 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9379 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9381 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9382 for output in tx.output.iter_mut() {
9383 // Make the confirmed funding transaction have a bogus script_pubkey
9384 output.script_pubkey = bitcoin::Script::new();
9387 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9388 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()));
9389 check_added_monitors!(nodes[1], 1);
9391 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()));
9392 check_added_monitors!(nodes[0], 1);
9394 let events_1 = nodes[0].node.get_and_clear_pending_events();
9395 assert_eq!(events_1.len(), 0);
9397 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9398 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9399 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9401 let expected_err = "funding tx had wrong script/value or output index";
9402 confirm_transaction_at(&nodes[1], &tx, 1);
9403 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9404 check_added_monitors!(nodes[1], 1);
9405 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9406 assert_eq!(events_2.len(), 1);
9407 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9408 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9409 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9410 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9411 } else { panic!(); }
9412 } else { panic!(); }
9413 assert_eq!(nodes[1].node.list_channels().len(), 0);
9416 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9417 // In the first version of the chain::Confirm interface, after a refactor was made to not
9418 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9419 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9420 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9421 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9422 // spending transaction until height N+1 (or greater). This was due to the way
9423 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9424 // spending transaction at the height the input transaction was confirmed at, not whether we
9425 // should broadcast a spending transaction at the current height.
9426 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9427 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9428 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9429 // until we learned about an additional block.
9431 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9432 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9433 let chanmon_cfgs = create_chanmon_cfgs(3);
9434 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9435 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9436 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9437 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9439 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9440 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9441 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9442 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9443 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9445 nodes[1].node.force_close_channel(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9446 check_closed_broadcast!(nodes[1], true);
9447 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9448 check_added_monitors!(nodes[1], 1);
9449 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9450 assert_eq!(node_txn.len(), 1);
9452 let conf_height = nodes[1].best_block_info().1;
9453 if !test_height_before_timelock {
9454 connect_blocks(&nodes[1], 24 * 6);
9456 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9457 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9458 if test_height_before_timelock {
9459 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9460 // generate any events or broadcast any transactions
9461 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9462 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9464 // We should broadcast an HTLC transaction spending our funding transaction first
9465 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9466 assert_eq!(spending_txn.len(), 2);
9467 assert_eq!(spending_txn[0], node_txn[0]);
9468 check_spends!(spending_txn[1], node_txn[0]);
9469 // We should also generate a SpendableOutputs event with the to_self output (as its
9471 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9472 assert_eq!(descriptor_spend_txn.len(), 1);
9474 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9475 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9476 // additional block built on top of the current chain.
9477 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9478 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9479 expect_pending_htlcs_forwardable!(nodes[1]);
9480 check_added_monitors!(nodes[1], 1);
9482 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9483 assert!(updates.update_add_htlcs.is_empty());
9484 assert!(updates.update_fulfill_htlcs.is_empty());
9485 assert_eq!(updates.update_fail_htlcs.len(), 1);
9486 assert!(updates.update_fail_malformed_htlcs.is_empty());
9487 assert!(updates.update_fee.is_none());
9488 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9489 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9490 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9495 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9496 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9497 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9501 fn test_forwardable_regen() {
9502 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9503 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9505 // We test it for both payment receipt and payment forwarding.
9507 let chanmon_cfgs = create_chanmon_cfgs(3);
9508 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9509 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9510 let persister: test_utils::TestPersister;
9511 let new_chain_monitor: test_utils::TestChainMonitor;
9512 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9513 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9514 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9515 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9517 // First send a payment to nodes[1]
9518 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9519 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9520 check_added_monitors!(nodes[0], 1);
9522 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9523 assert_eq!(events.len(), 1);
9524 let payment_event = SendEvent::from_event(events.pop().unwrap());
9525 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9526 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9528 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9530 // Next send a payment which is forwarded by nodes[1]
9531 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9532 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9533 check_added_monitors!(nodes[0], 1);
9535 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9536 assert_eq!(events.len(), 1);
9537 let payment_event = SendEvent::from_event(events.pop().unwrap());
9538 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9539 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9541 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9543 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9545 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9546 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9547 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9549 let nodes_1_serialized = nodes[1].node.encode();
9550 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9551 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9552 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9553 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9555 persister = test_utils::TestPersister::new();
9556 let keys_manager = &chanmon_cfgs[1].keys_manager;
9557 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);
9558 nodes[1].chain_monitor = &new_chain_monitor;
9560 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9561 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9562 &mut chan_0_monitor_read, keys_manager).unwrap();
9563 assert!(chan_0_monitor_read.is_empty());
9564 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9565 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9566 &mut chan_1_monitor_read, keys_manager).unwrap();
9567 assert!(chan_1_monitor_read.is_empty());
9569 let mut nodes_1_read = &nodes_1_serialized[..];
9570 let (_, nodes_1_deserialized_tmp) = {
9571 let mut channel_monitors = HashMap::new();
9572 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9573 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9574 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9575 default_config: UserConfig::default(),
9577 fee_estimator: node_cfgs[1].fee_estimator,
9578 chain_monitor: nodes[1].chain_monitor,
9579 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9580 logger: nodes[1].logger,
9584 nodes_1_deserialized = nodes_1_deserialized_tmp;
9585 assert!(nodes_1_read.is_empty());
9587 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9588 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9589 nodes[1].node = &nodes_1_deserialized;
9590 check_added_monitors!(nodes[1], 2);
9592 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9593 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9594 // the commitment state.
9595 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9597 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9599 expect_pending_htlcs_forwardable!(nodes[1]);
9600 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9601 check_added_monitors!(nodes[1], 1);
9603 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9604 assert_eq!(events.len(), 1);
9605 let payment_event = SendEvent::from_event(events.pop().unwrap());
9606 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9607 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9608 expect_pending_htlcs_forwardable!(nodes[2]);
9609 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9611 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9612 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9615 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9616 let chanmon_cfgs = create_chanmon_cfgs(2);
9617 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9618 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9619 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9621 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9623 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9624 .with_features(InvoiceFeatures::known());
9625 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9627 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9630 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9631 check_added_monitors!(nodes[0], 1);
9632 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9633 assert_eq!(events.len(), 1);
9634 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9635 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9636 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9638 expect_pending_htlcs_forwardable!(nodes[1]);
9639 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9642 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9643 check_added_monitors!(nodes[0], 1);
9644 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9645 assert_eq!(events.len(), 1);
9646 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9647 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9648 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9649 // At this point, nodes[1] would notice it has too much value for the payment. It will
9650 // assume the second is a privacy attack (no longer particularly relevant
9651 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9652 // the first HTLC delivered above.
9655 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9656 nodes[1].node.process_pending_htlc_forwards();
9658 if test_for_second_fail_panic {
9659 // Now we go fail back the first HTLC from the user end.
9660 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9662 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9663 nodes[1].node.process_pending_htlc_forwards();
9665 check_added_monitors!(nodes[1], 1);
9666 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9667 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9669 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9670 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9671 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9673 let failure_events = nodes[0].node.get_and_clear_pending_events();
9674 assert_eq!(failure_events.len(), 2);
9675 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9676 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9678 // Let the second HTLC fail and claim the first
9679 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9680 nodes[1].node.process_pending_htlc_forwards();
9682 check_added_monitors!(nodes[1], 1);
9683 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9684 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9685 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9687 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9689 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9694 fn test_dup_htlc_second_fail_panic() {
9695 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9696 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9697 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9698 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9699 do_test_dup_htlc_second_rejected(true);
9703 fn test_dup_htlc_second_rejected() {
9704 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9705 // simply reject the second HTLC but are still able to claim the first HTLC.
9706 do_test_dup_htlc_second_rejected(false);
9710 fn test_inconsistent_mpp_params() {
9711 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9712 // such HTLC and allow the second to stay.
9713 let chanmon_cfgs = create_chanmon_cfgs(4);
9714 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9715 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9716 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9718 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9719 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9720 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9721 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9723 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9724 .with_features(InvoiceFeatures::known());
9725 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9726 assert_eq!(route.paths.len(), 2);
9727 route.paths.sort_by(|path_a, _| {
9728 // Sort the path so that the path through nodes[1] comes first
9729 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9730 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9732 let payment_params_opt = Some(payment_params);
9734 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9736 let cur_height = nodes[0].best_block_info().1;
9737 let payment_id = PaymentId([42; 32]);
9739 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();
9740 check_added_monitors!(nodes[0], 1);
9742 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9743 assert_eq!(events.len(), 1);
9744 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9746 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9749 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();
9750 check_added_monitors!(nodes[0], 1);
9752 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9753 assert_eq!(events.len(), 1);
9754 let payment_event = SendEvent::from_event(events.pop().unwrap());
9756 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9757 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9759 expect_pending_htlcs_forwardable!(nodes[2]);
9760 check_added_monitors!(nodes[2], 1);
9762 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9763 assert_eq!(events.len(), 1);
9764 let payment_event = SendEvent::from_event(events.pop().unwrap());
9766 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9767 check_added_monitors!(nodes[3], 0);
9768 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9770 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9771 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9772 // post-payment_secrets) and fail back the new HTLC.
9774 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9775 nodes[3].node.process_pending_htlc_forwards();
9776 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9777 nodes[3].node.process_pending_htlc_forwards();
9779 check_added_monitors!(nodes[3], 1);
9781 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9782 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9783 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9785 expect_pending_htlcs_forwardable!(nodes[2]);
9786 check_added_monitors!(nodes[2], 1);
9788 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9789 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9790 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9792 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9794 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();
9795 check_added_monitors!(nodes[0], 1);
9797 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9798 assert_eq!(events.len(), 1);
9799 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9801 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9805 fn test_keysend_payments_to_public_node() {
9806 let chanmon_cfgs = create_chanmon_cfgs(2);
9807 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9808 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9809 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9811 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9812 let network_graph = nodes[0].network_graph;
9813 let payer_pubkey = nodes[0].node.get_our_node_id();
9814 let payee_pubkey = nodes[1].node.get_our_node_id();
9815 let route_params = RouteParameters {
9816 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9817 final_value_msat: 10000,
9818 final_cltv_expiry_delta: 40,
9820 let scorer = test_utils::TestScorer::with_penalty(0);
9821 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9822 let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9824 let test_preimage = PaymentPreimage([42; 32]);
9825 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9826 check_added_monitors!(nodes[0], 1);
9827 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9828 assert_eq!(events.len(), 1);
9829 let event = events.pop().unwrap();
9830 let path = vec![&nodes[1]];
9831 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9832 claim_payment(&nodes[0], &path, test_preimage);
9836 fn test_keysend_payments_to_private_node() {
9837 let chanmon_cfgs = create_chanmon_cfgs(2);
9838 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9839 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9840 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9842 let payer_pubkey = nodes[0].node.get_our_node_id();
9843 let payee_pubkey = nodes[1].node.get_our_node_id();
9844 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9845 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9847 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9848 let route_params = RouteParameters {
9849 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9850 final_value_msat: 10000,
9851 final_cltv_expiry_delta: 40,
9853 let network_graph = nodes[0].network_graph;
9854 let first_hops = nodes[0].node.list_usable_channels();
9855 let scorer = test_utils::TestScorer::with_penalty(0);
9856 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9857 let route = find_route(
9858 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9859 nodes[0].logger, &scorer, &random_seed_bytes
9862 let test_preimage = PaymentPreimage([42; 32]);
9863 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9864 check_added_monitors!(nodes[0], 1);
9865 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9866 assert_eq!(events.len(), 1);
9867 let event = events.pop().unwrap();
9868 let path = vec![&nodes[1]];
9869 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9870 claim_payment(&nodes[0], &path, test_preimage);
9874 fn test_double_partial_claim() {
9875 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9876 // time out, the sender resends only some of the MPP parts, then the user processes the
9877 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9879 let chanmon_cfgs = create_chanmon_cfgs(4);
9880 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9881 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9882 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9884 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9885 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9886 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9887 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9889 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9890 assert_eq!(route.paths.len(), 2);
9891 route.paths.sort_by(|path_a, _| {
9892 // Sort the path so that the path through nodes[1] comes first
9893 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9894 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9897 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9898 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9899 // amount of time to respond to.
9901 // Connect some blocks to time out the payment
9902 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9903 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9905 expect_pending_htlcs_forwardable!(nodes[3]);
9907 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9909 // nodes[1] now retries one of the two paths...
9910 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9911 check_added_monitors!(nodes[0], 2);
9913 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9914 assert_eq!(events.len(), 2);
9915 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9917 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9918 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9919 nodes[3].node.claim_funds(payment_preimage);
9920 check_added_monitors!(nodes[3], 0);
9921 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9924 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
9925 // Test what happens if a node receives an MPP payment, claims it, but crashes before
9926 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
9927 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
9928 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
9929 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
9930 // not have the preimage tied to the still-pending HTLC.
9932 // To get to the correct state, on startup we should propagate the preimage to the
9933 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
9934 // receiving the preimage without a state update.
9936 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
9937 // definitely claimed.
9938 let chanmon_cfgs = create_chanmon_cfgs(4);
9939 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9940 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9942 let persister: test_utils::TestPersister;
9943 let new_chain_monitor: test_utils::TestChainMonitor;
9944 let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9946 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9948 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9949 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9950 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9951 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9953 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
9954 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9955 assert_eq!(route.paths.len(), 2);
9956 route.paths.sort_by(|path_a, _| {
9957 // Sort the path so that the path through nodes[1] comes first
9958 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9959 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9962 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9963 check_added_monitors!(nodes[0], 2);
9965 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
9966 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
9967 assert_eq!(send_events.len(), 2);
9968 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);
9969 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);
9971 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
9972 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
9973 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
9974 if !persist_both_monitors {
9975 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
9976 if outpoint.to_channel_id() == chan_id_not_persisted {
9977 assert!(original_monitor.0.is_empty());
9978 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
9983 let mut original_manager = test_utils::TestVecWriter(Vec::new());
9984 nodes[3].node.write(&mut original_manager).unwrap();
9986 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
9988 nodes[3].node.claim_funds(payment_preimage);
9989 check_added_monitors!(nodes[3], 2);
9990 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
9992 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
9993 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
9994 // with the old ChannelManager.
9995 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
9996 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
9997 if outpoint.to_channel_id() == chan_id_persisted {
9998 assert!(updated_monitor.0.is_empty());
9999 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10002 // If `persist_both_monitors` is set, get the second monitor here as well
10003 if persist_both_monitors {
10004 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10005 if outpoint.to_channel_id() == chan_id_not_persisted {
10006 assert!(original_monitor.0.is_empty());
10007 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10012 // Now restart nodes[3].
10013 persister = test_utils::TestPersister::new();
10014 let keys_manager = &chanmon_cfgs[3].keys_manager;
10015 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);
10016 nodes[3].chain_monitor = &new_chain_monitor;
10017 let mut monitors = Vec::new();
10018 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10019 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10020 monitors.push(deserialized_monitor);
10023 let config = UserConfig::default();
10024 nodes_3_deserialized = {
10025 let mut channel_monitors = HashMap::new();
10026 for monitor in monitors.iter_mut() {
10027 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10029 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10030 default_config: config,
10032 fee_estimator: node_cfgs[3].fee_estimator,
10033 chain_monitor: nodes[3].chain_monitor,
10034 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10035 logger: nodes[3].logger,
10039 nodes[3].node = &nodes_3_deserialized;
10041 for monitor in monitors {
10042 // On startup the preimage should have been copied into the non-persisted monitor:
10043 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10044 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10046 check_added_monitors!(nodes[3], 2);
10048 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10049 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10051 // During deserialization, we should have closed one channel and broadcast its latest
10052 // commitment transaction. We should also still have the original PaymentReceived event we
10053 // never finished processing.
10054 let events = nodes[3].node.get_and_clear_pending_events();
10055 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10056 if let Event::PaymentReceived { amt: 15_000_000, .. } = events[0] { } else { panic!(); }
10057 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10058 if persist_both_monitors {
10059 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10062 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10063 // ChannelManager prior to handling the original one.
10064 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amt: 15_000_000, .. } = events[if persist_both_monitors { 3 } else { 2 }] {
10065 assert_eq!(payment_hash, our_payment_hash);
10066 } else { panic!(); }
10068 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10069 if !persist_both_monitors {
10070 // If one of the two channels is still live, reveal the payment preimage over it.
10072 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10073 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10074 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10075 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10077 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10078 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10079 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10081 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10083 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10084 // claim should fly.
10085 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10086 check_added_monitors!(nodes[3], 1);
10087 assert_eq!(ds_msgs.len(), 2);
10088 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10090 let cs_updates = match ds_msgs[0] {
10091 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10092 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10093 check_added_monitors!(nodes[2], 1);
10094 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10095 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10096 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10102 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10103 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10104 expect_payment_sent!(nodes[0], payment_preimage);
10109 fn test_partial_claim_before_restart() {
10110 do_test_partial_claim_before_restart(false);
10111 do_test_partial_claim_before_restart(true);
10114 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10115 #[derive(Clone, Copy, PartialEq)]
10116 enum ExposureEvent {
10117 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10119 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10121 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10122 AtUpdateFeeOutbound,
10125 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10126 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10129 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10130 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10131 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10132 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10133 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10134 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10135 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10136 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10138 let chanmon_cfgs = create_chanmon_cfgs(2);
10139 let mut config = test_default_channel_config();
10140 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10141 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10142 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10143 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10145 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10146 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10147 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10148 open_channel.max_accepted_htlcs = 60;
10150 open_channel.dust_limit_satoshis = 546;
10152 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10153 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10154 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10156 let opt_anchors = false;
10158 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10161 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10162 chan.holder_dust_limit_satoshis = 546;
10166 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10167 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()));
10168 check_added_monitors!(nodes[1], 1);
10170 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()));
10171 check_added_monitors!(nodes[0], 1);
10173 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10174 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
10175 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10177 let dust_buffer_feerate = {
10178 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10179 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10180 chan.get_dust_buffer_feerate(None) as u64
10182 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;
10183 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10185 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;
10186 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10188 let dust_htlc_on_counterparty_tx: u64 = 25;
10189 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10192 if dust_outbound_balance {
10193 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10194 // Outbound dust balance: 4372 sats
10195 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10196 for i in 0..dust_outbound_htlc_on_holder_tx {
10197 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10198 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10201 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10202 // Inbound dust balance: 4372 sats
10203 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10204 for _ in 0..dust_inbound_htlc_on_holder_tx {
10205 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10209 if dust_outbound_balance {
10210 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10211 // Outbound dust balance: 5000 sats
10212 for i in 0..dust_htlc_on_counterparty_tx {
10213 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10214 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10217 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10218 // Inbound dust balance: 5000 sats
10219 for _ in 0..dust_htlc_on_counterparty_tx {
10220 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10225 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10226 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10227 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 });
10228 let mut config = UserConfig::default();
10229 // With default dust exposure: 5000 sats
10231 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10232 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10233 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_options.max_dust_htlc_exposure_msat)));
10235 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_options.max_dust_htlc_exposure_msat)));
10237 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10238 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 });
10239 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10240 check_added_monitors!(nodes[1], 1);
10241 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10242 assert_eq!(events.len(), 1);
10243 let payment_event = SendEvent::from_event(events.remove(0));
10244 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10245 // With default dust exposure: 5000 sats
10247 // Outbound dust balance: 6399 sats
10248 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10249 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10250 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_options.max_dust_htlc_exposure_msat), 1);
10252 // Outbound dust balance: 5200 sats
10253 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_options.max_dust_htlc_exposure_msat), 1);
10255 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10256 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10257 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10259 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10260 *feerate_lock = *feerate_lock * 10;
10262 nodes[0].node.timer_tick_occurred();
10263 check_added_monitors!(nodes[0], 1);
10264 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);
10267 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10268 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10269 added_monitors.clear();
10273 fn test_max_dust_htlc_exposure() {
10274 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10275 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10276 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10277 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10278 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10279 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10280 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10281 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10282 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10283 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10284 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10285 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);