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], 100000, 42);
520 if steps & 0x0f == 3 { return; }
521 nodes[0].node.funding_transaction_generated(&temporary_channel_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 check_added_monitors!(nodes[0], 1);
1264 // Broadcast node 1 commitment txn
1265 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1267 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1268 let mut has_both_htlcs = 0; // check htlcs match ones committed
1269 for outp in remote_txn[0].output.iter() {
1270 if outp.value == 800_000 / 1000 {
1271 has_both_htlcs += 1;
1272 } else if outp.value == 900_000 / 1000 {
1273 has_both_htlcs += 1;
1276 assert_eq!(has_both_htlcs, 2);
1278 mine_transaction(&nodes[0], &remote_txn[0]);
1279 check_added_monitors!(nodes[0], 1);
1280 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1281 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1283 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1284 assert_eq!(claim_txn.len(), 8);
1286 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1288 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1289 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1291 let bump_tx = if claim_txn[1] == claim_txn[4] {
1292 assert_eq!(claim_txn[1], claim_txn[4]);
1293 assert_eq!(claim_txn[2], claim_txn[5]);
1295 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1297 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1300 assert_eq!(claim_txn[1], claim_txn[3]);
1301 assert_eq!(claim_txn[2], claim_txn[4]);
1303 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1305 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1310 assert_eq!(claim_txn[0].input.len(), 1);
1311 assert_eq!(bump_tx.input.len(), 1);
1312 assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1314 assert_eq!(claim_txn[0].input.len(), 1);
1315 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1316 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1318 assert_eq!(claim_txn[6].input.len(), 1);
1319 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1320 check_spends!(claim_txn[6], remote_txn[0]);
1321 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1323 let events = nodes[0].node.get_and_clear_pending_msg_events();
1324 assert_eq!(events.len(), 3);
1327 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1328 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1329 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1330 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1332 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, .. } } => {
1333 assert!(update_add_htlcs.is_empty());
1334 assert!(update_fail_htlcs.is_empty());
1335 assert_eq!(update_fulfill_htlcs.len(), 1);
1336 assert!(update_fail_malformed_htlcs.is_empty());
1337 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1339 _ => panic!("Unexpected event"),
1345 fn test_basic_channel_reserve() {
1346 let chanmon_cfgs = create_chanmon_cfgs(2);
1347 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1348 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1349 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1350 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1352 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1353 let channel_reserve = chan_stat.channel_reserve_msat;
1355 // The 2* and +1 are for the fee spike reserve.
1356 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1357 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1358 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1359 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1361 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1363 &APIError::ChannelUnavailable{ref err} =>
1364 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1365 _ => panic!("Unexpected error variant"),
1368 _ => panic!("Unexpected error variant"),
1370 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1371 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);
1373 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1377 fn test_fee_spike_violation_fails_htlc() {
1378 let chanmon_cfgs = create_chanmon_cfgs(2);
1379 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1380 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1381 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1382 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1384 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1385 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1386 let secp_ctx = Secp256k1::new();
1387 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1389 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1391 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1392 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1393 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1394 let msg = msgs::UpdateAddHTLC {
1397 amount_msat: htlc_msat,
1398 payment_hash: payment_hash,
1399 cltv_expiry: htlc_cltv,
1400 onion_routing_packet: onion_packet,
1403 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1405 // Now manually create the commitment_signed message corresponding to the update_add
1406 // nodes[0] just sent. In the code for construction of this message, "local" refers
1407 // to the sender of the message, and "remote" refers to the receiver.
1409 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1411 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1413 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1414 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1415 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1416 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1417 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1418 let chan_signer = local_chan.get_signer();
1419 // Make the signer believe we validated another commitment, so we can release the secret
1420 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1422 let pubkeys = chan_signer.pubkeys();
1423 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1424 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1425 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1426 chan_signer.pubkeys().funding_pubkey)
1428 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1429 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1430 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1431 let chan_signer = remote_chan.get_signer();
1432 let pubkeys = chan_signer.pubkeys();
1433 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1434 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1435 chan_signer.pubkeys().funding_pubkey)
1438 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1439 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1440 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1442 // Build the remote commitment transaction so we can sign it, and then later use the
1443 // signature for the commitment_signed message.
1444 let local_chan_balance = 1313;
1446 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1448 amount_msat: 3460001,
1449 cltv_expiry: htlc_cltv,
1451 transaction_output_index: Some(1),
1454 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1457 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1458 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1459 let local_chan_signer = local_chan.get_signer();
1460 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1464 local_chan.opt_anchors(), local_funding, remote_funding,
1465 commit_tx_keys.clone(),
1467 &mut vec![(accepted_htlc_info, ())],
1468 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1470 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1473 let commit_signed_msg = msgs::CommitmentSigned {
1476 htlc_signatures: res.1
1479 // Send the commitment_signed message to the nodes[1].
1480 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1481 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1483 // Send the RAA to nodes[1].
1484 let raa_msg = msgs::RevokeAndACK {
1486 per_commitment_secret: local_secret,
1487 next_per_commitment_point: next_local_point
1489 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1491 let events = nodes[1].node.get_and_clear_pending_msg_events();
1492 assert_eq!(events.len(), 1);
1493 // Make sure the HTLC failed in the way we expect.
1495 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1496 assert_eq!(update_fail_htlcs.len(), 1);
1497 update_fail_htlcs[0].clone()
1499 _ => panic!("Unexpected event"),
1501 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1502 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1504 check_added_monitors!(nodes[1], 2);
1508 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1509 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1510 // Set the fee rate for the channel very high, to the point where the fundee
1511 // sending any above-dust amount would result in a channel reserve violation.
1512 // In this test we check that we would be prevented from sending an HTLC in
1514 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1517 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1519 let opt_anchors = false;
1521 let mut push_amt = 100_000_000;
1522 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1523 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1525 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1527 // Sending exactly enough to hit the reserve amount should be accepted
1528 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1529 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1532 // However one more HTLC should be significantly over the reserve amount and fail.
1533 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1534 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1535 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1536 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1537 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);
1541 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1542 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1543 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1546 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1548 let opt_anchors = false;
1550 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1551 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1552 // transaction fee with 0 HTLCs (183 sats)).
1553 let mut push_amt = 100_000_000;
1554 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1555 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1556 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1558 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1559 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1560 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1563 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1564 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1565 let secp_ctx = Secp256k1::new();
1566 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1567 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1568 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1569 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1570 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1571 let msg = msgs::UpdateAddHTLC {
1573 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1574 amount_msat: htlc_msat,
1575 payment_hash: payment_hash,
1576 cltv_expiry: htlc_cltv,
1577 onion_routing_packet: onion_packet,
1580 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1581 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1582 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);
1583 assert_eq!(nodes[0].node.list_channels().len(), 0);
1584 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1585 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1586 check_added_monitors!(nodes[0], 1);
1587 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() });
1591 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1592 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1593 // calculating our commitment transaction fee (this was previously broken).
1594 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1595 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1599 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1601 let opt_anchors = false;
1603 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1604 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1605 // transaction fee with 0 HTLCs (183 sats)).
1606 let mut push_amt = 100_000_000;
1607 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1608 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1609 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1611 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1612 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1613 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1614 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1615 // commitment transaction fee.
1616 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1618 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1619 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1620 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1623 // One more than the dust amt should fail, however.
1624 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1625 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1626 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1630 fn test_chan_init_feerate_unaffordability() {
1631 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1632 // channel reserve and feerate requirements.
1633 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1634 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1635 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1637 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1639 let opt_anchors = false;
1641 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1643 let mut push_amt = 100_000_000;
1644 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1645 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1646 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1648 // During open, we don't have a "counterparty channel reserve" to check against, so that
1649 // requirement only comes into play on the open_channel handling side.
1650 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1651 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1652 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1653 open_channel_msg.push_msat += 1;
1654 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1656 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1657 assert_eq!(msg_events.len(), 1);
1658 match msg_events[0] {
1659 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1660 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1662 _ => panic!("Unexpected event"),
1667 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1668 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1669 // calculating our counterparty's commitment transaction fee (this was previously broken).
1670 let chanmon_cfgs = create_chanmon_cfgs(2);
1671 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1672 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1673 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1674 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1676 let payment_amt = 46000; // Dust amount
1677 // In the previous code, these first four payments would succeed.
1678 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1679 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1684 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1691 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1692 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1693 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1697 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1698 let chanmon_cfgs = create_chanmon_cfgs(3);
1699 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1700 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1701 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1702 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1703 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1706 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1707 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1708 let feerate = get_feerate!(nodes[0], chan.2);
1709 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1711 // Add a 2* and +1 for the fee spike reserve.
1712 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1713 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;
1714 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1716 // Add a pending HTLC.
1717 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1718 let payment_event_1 = {
1719 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1720 check_added_monitors!(nodes[0], 1);
1722 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1723 assert_eq!(events.len(), 1);
1724 SendEvent::from_event(events.remove(0))
1726 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1728 // Attempt to trigger a channel reserve violation --> payment failure.
1729 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1730 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;
1731 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1732 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1734 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1735 let secp_ctx = Secp256k1::new();
1736 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1737 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1738 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1739 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1740 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1741 let msg = msgs::UpdateAddHTLC {
1744 amount_msat: htlc_msat + 1,
1745 payment_hash: our_payment_hash_1,
1746 cltv_expiry: htlc_cltv,
1747 onion_routing_packet: onion_packet,
1750 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1751 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1752 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1753 assert_eq!(nodes[1].node.list_channels().len(), 1);
1754 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1755 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1756 check_added_monitors!(nodes[1], 1);
1757 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1761 fn test_inbound_outbound_capacity_is_not_zero() {
1762 let chanmon_cfgs = create_chanmon_cfgs(2);
1763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1765 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1766 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1767 let channels0 = node_chanmgrs[0].list_channels();
1768 let channels1 = node_chanmgrs[1].list_channels();
1769 assert_eq!(channels0.len(), 1);
1770 assert_eq!(channels1.len(), 1);
1772 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1773 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1774 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1776 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1777 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1780 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1781 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1785 fn test_channel_reserve_holding_cell_htlcs() {
1786 let chanmon_cfgs = create_chanmon_cfgs(3);
1787 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1788 // When this test was written, the default base fee floated based on the HTLC count.
1789 // It is now fixed, so we simply set the fee to the expected value here.
1790 let mut config = test_default_channel_config();
1791 config.channel_options.forwarding_fee_base_msat = 239;
1792 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1793 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1794 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1795 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1797 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1798 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1800 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1801 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1803 macro_rules! expect_forward {
1805 let mut events = $node.node.get_and_clear_pending_msg_events();
1806 assert_eq!(events.len(), 1);
1807 check_added_monitors!($node, 1);
1808 let payment_event = SendEvent::from_event(events.remove(0));
1813 let feemsat = 239; // set above
1814 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1815 let feerate = get_feerate!(nodes[0], chan_1.2);
1816 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1818 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1820 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1822 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1823 route.paths[0].last_mut().unwrap().fee_msat += 1;
1824 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1825 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1826 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)));
1827 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1828 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);
1831 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1832 // nodes[0]'s wealth
1834 let amt_msat = recv_value_0 + total_fee_msat;
1835 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1836 // Also, ensure that each payment has enough to be over the dust limit to
1837 // ensure it'll be included in each commit tx fee calculation.
1838 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1839 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1840 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1843 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1845 let (stat01_, stat11_, stat12_, stat22_) = (
1846 get_channel_value_stat!(nodes[0], chan_1.2),
1847 get_channel_value_stat!(nodes[1], chan_1.2),
1848 get_channel_value_stat!(nodes[1], chan_2.2),
1849 get_channel_value_stat!(nodes[2], chan_2.2),
1852 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1853 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1854 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1855 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1856 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1859 // adding pending output.
1860 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1861 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1862 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1863 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1864 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1865 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1866 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1867 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1868 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1870 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1871 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1872 let amt_msat_1 = recv_value_1 + total_fee_msat;
1874 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);
1875 let payment_event_1 = {
1876 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1877 check_added_monitors!(nodes[0], 1);
1879 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1880 assert_eq!(events.len(), 1);
1881 SendEvent::from_event(events.remove(0))
1883 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1885 // channel reserve test with htlc pending output > 0
1886 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1888 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1889 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1890 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1891 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1894 // split the rest to test holding cell
1895 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1896 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1897 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1898 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1900 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1901 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);
1904 // now see if they go through on both sides
1905 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);
1906 // but this will stuck in the holding cell
1907 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1908 check_added_monitors!(nodes[0], 0);
1909 let events = nodes[0].node.get_and_clear_pending_events();
1910 assert_eq!(events.len(), 0);
1912 // test with outbound holding cell amount > 0
1914 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1915 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1916 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1917 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1918 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);
1921 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);
1922 // this will also stuck in the holding cell
1923 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1924 check_added_monitors!(nodes[0], 0);
1925 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1926 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1928 // flush the pending htlc
1929 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1930 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1931 check_added_monitors!(nodes[1], 1);
1933 // the pending htlc should be promoted to committed
1934 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1935 check_added_monitors!(nodes[0], 1);
1936 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1939 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1940 // No commitment_signed so get_event_msg's assert(len == 1) passes
1941 check_added_monitors!(nodes[0], 1);
1943 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1944 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1945 check_added_monitors!(nodes[1], 1);
1947 expect_pending_htlcs_forwardable!(nodes[1]);
1949 let ref payment_event_11 = expect_forward!(nodes[1]);
1950 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1951 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1953 expect_pending_htlcs_forwardable!(nodes[2]);
1954 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1956 // flush the htlcs in the holding cell
1957 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1958 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1959 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1960 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1961 expect_pending_htlcs_forwardable!(nodes[1]);
1963 let ref payment_event_3 = expect_forward!(nodes[1]);
1964 assert_eq!(payment_event_3.msgs.len(), 2);
1965 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1966 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1968 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1969 expect_pending_htlcs_forwardable!(nodes[2]);
1971 let events = nodes[2].node.get_and_clear_pending_events();
1972 assert_eq!(events.len(), 2);
1974 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1975 assert_eq!(our_payment_hash_21, *payment_hash);
1976 assert_eq!(recv_value_21, amt);
1978 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1979 assert!(payment_preimage.is_none());
1980 assert_eq!(our_payment_secret_21, *payment_secret);
1982 _ => panic!("expected PaymentPurpose::InvoicePayment")
1985 _ => panic!("Unexpected event"),
1988 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1989 assert_eq!(our_payment_hash_22, *payment_hash);
1990 assert_eq!(recv_value_22, amt);
1992 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1993 assert!(payment_preimage.is_none());
1994 assert_eq!(our_payment_secret_22, *payment_secret);
1996 _ => panic!("expected PaymentPurpose::InvoicePayment")
1999 _ => panic!("Unexpected event"),
2002 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2003 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2004 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2006 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2007 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2008 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2010 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2011 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);
2012 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2013 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2014 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2016 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2017 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2021 fn channel_reserve_in_flight_removes() {
2022 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2023 // can send to its counterparty, but due to update ordering, the other side may not yet have
2024 // considered those HTLCs fully removed.
2025 // This tests that we don't count HTLCs which will not be included in the next remote
2026 // commitment transaction towards the reserve value (as it implies no commitment transaction
2027 // will be generated which violates the remote reserve value).
2028 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2030 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2031 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2032 // you only consider the value of the first HTLC, it may not),
2033 // * start routing a third HTLC from A to B,
2034 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2035 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2036 // * deliver the first fulfill from B
2037 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2039 // * deliver A's response CS and RAA.
2040 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2041 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2042 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2043 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2044 let chanmon_cfgs = create_chanmon_cfgs(2);
2045 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2046 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2047 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2048 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2050 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2051 // Route the first two HTLCs.
2052 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2053 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2055 // Start routing the third HTLC (this is just used to get everyone in the right state).
2056 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2058 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2059 check_added_monitors!(nodes[0], 1);
2060 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2061 assert_eq!(events.len(), 1);
2062 SendEvent::from_event(events.remove(0))
2065 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2066 // initial fulfill/CS.
2067 assert!(nodes[1].node.claim_funds(payment_preimage_1));
2068 check_added_monitors!(nodes[1], 1);
2069 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2071 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2072 // remove the second HTLC when we send the HTLC back from B to A.
2073 assert!(nodes[1].node.claim_funds(payment_preimage_2));
2074 check_added_monitors!(nodes[1], 1);
2075 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2077 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2078 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2079 check_added_monitors!(nodes[0], 1);
2080 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2081 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2083 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2084 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2085 check_added_monitors!(nodes[1], 1);
2086 // B is already AwaitingRAA, so cant generate a CS here
2087 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2089 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2090 check_added_monitors!(nodes[1], 1);
2091 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2093 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2094 check_added_monitors!(nodes[0], 1);
2095 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2097 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2098 check_added_monitors!(nodes[1], 1);
2099 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2101 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2102 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2103 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2104 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2105 // on-chain as necessary).
2106 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2107 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2108 check_added_monitors!(nodes[0], 1);
2109 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2110 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2112 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2113 check_added_monitors!(nodes[1], 1);
2114 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2116 expect_pending_htlcs_forwardable!(nodes[1]);
2117 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2119 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2120 // resolve the second HTLC from A's point of view.
2121 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2122 check_added_monitors!(nodes[0], 1);
2123 expect_payment_path_successful!(nodes[0]);
2124 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2126 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2127 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2128 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2130 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2131 check_added_monitors!(nodes[1], 1);
2132 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2133 assert_eq!(events.len(), 1);
2134 SendEvent::from_event(events.remove(0))
2137 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2138 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2139 check_added_monitors!(nodes[0], 1);
2140 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2142 // Now just resolve all the outstanding messages/HTLCs for completeness...
2144 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2145 check_added_monitors!(nodes[1], 1);
2146 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2148 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2149 check_added_monitors!(nodes[1], 1);
2151 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2152 check_added_monitors!(nodes[0], 1);
2153 expect_payment_path_successful!(nodes[0]);
2154 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2156 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2157 check_added_monitors!(nodes[1], 1);
2158 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2160 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2161 check_added_monitors!(nodes[0], 1);
2163 expect_pending_htlcs_forwardable!(nodes[0]);
2164 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2166 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2167 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2171 fn channel_monitor_network_test() {
2172 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2173 // tests that ChannelMonitor is able to recover from various states.
2174 let chanmon_cfgs = create_chanmon_cfgs(5);
2175 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2176 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2177 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2179 // Create some initial channels
2180 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2181 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2182 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2183 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2185 // Make sure all nodes are at the same starting height
2186 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2187 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2188 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2189 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2190 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2192 // Rebalance the network a bit by relaying one payment through all the channels...
2193 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2195 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2196 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2198 // Simple case with no pending HTLCs:
2199 nodes[1].node.force_close_channel(&chan_1.2).unwrap();
2200 check_added_monitors!(nodes[1], 1);
2201 check_closed_broadcast!(nodes[1], true);
2203 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2204 assert_eq!(node_txn.len(), 1);
2205 mine_transaction(&nodes[0], &node_txn[0]);
2206 check_added_monitors!(nodes[0], 1);
2207 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2209 check_closed_broadcast!(nodes[0], true);
2210 assert_eq!(nodes[0].node.list_channels().len(), 0);
2211 assert_eq!(nodes[1].node.list_channels().len(), 1);
2212 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2213 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2215 // One pending HTLC is discarded by the force-close:
2216 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2218 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2219 // broadcasted until we reach the timelock time).
2220 nodes[1].node.force_close_channel(&chan_2.2).unwrap();
2221 check_closed_broadcast!(nodes[1], true);
2222 check_added_monitors!(nodes[1], 1);
2224 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2225 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2226 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2227 mine_transaction(&nodes[2], &node_txn[0]);
2228 check_added_monitors!(nodes[2], 1);
2229 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2231 check_closed_broadcast!(nodes[2], true);
2232 assert_eq!(nodes[1].node.list_channels().len(), 0);
2233 assert_eq!(nodes[2].node.list_channels().len(), 1);
2234 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2235 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2237 macro_rules! claim_funds {
2238 ($node: expr, $prev_node: expr, $preimage: expr) => {
2240 assert!($node.node.claim_funds($preimage));
2241 check_added_monitors!($node, 1);
2243 let events = $node.node.get_and_clear_pending_msg_events();
2244 assert_eq!(events.len(), 1);
2246 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2247 assert!(update_add_htlcs.is_empty());
2248 assert!(update_fail_htlcs.is_empty());
2249 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2251 _ => panic!("Unexpected event"),
2257 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2258 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2259 nodes[2].node.force_close_channel(&chan_3.2).unwrap();
2260 check_added_monitors!(nodes[2], 1);
2261 check_closed_broadcast!(nodes[2], true);
2262 let node2_commitment_txid;
2264 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2265 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2267 node2_commitment_txid = node_txn[0].txid();
2269 // Claim the payment on nodes[3], giving it knowledge of the preimage
2270 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2271 mine_transaction(&nodes[3], &node_txn[0]);
2272 check_added_monitors!(nodes[3], 1);
2273 check_preimage_claim(&nodes[3], &node_txn);
2275 check_closed_broadcast!(nodes[3], true);
2276 assert_eq!(nodes[2].node.list_channels().len(), 0);
2277 assert_eq!(nodes[3].node.list_channels().len(), 1);
2278 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2279 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2281 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2282 // confusing us in the following tests.
2283 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2285 // One pending HTLC to time out:
2286 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2287 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2290 let (close_chan_update_1, close_chan_update_2) = {
2291 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2292 let events = nodes[3].node.get_and_clear_pending_msg_events();
2293 assert_eq!(events.len(), 2);
2294 let close_chan_update_1 = match events[0] {
2295 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2298 _ => panic!("Unexpected event"),
2301 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2302 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2304 _ => panic!("Unexpected event"),
2306 check_added_monitors!(nodes[3], 1);
2308 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2310 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2311 node_txn.retain(|tx| {
2312 if tx.input[0].previous_output.txid == node2_commitment_txid {
2318 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2320 // Claim the payment on nodes[4], giving it knowledge of the preimage
2321 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2323 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2324 let events = nodes[4].node.get_and_clear_pending_msg_events();
2325 assert_eq!(events.len(), 2);
2326 let close_chan_update_2 = match events[0] {
2327 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2330 _ => panic!("Unexpected event"),
2333 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2336 _ => panic!("Unexpected event"),
2338 check_added_monitors!(nodes[4], 1);
2339 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2341 mine_transaction(&nodes[4], &node_txn[0]);
2342 check_preimage_claim(&nodes[4], &node_txn);
2343 (close_chan_update_1, close_chan_update_2)
2345 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2346 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2347 assert_eq!(nodes[3].node.list_channels().len(), 0);
2348 assert_eq!(nodes[4].node.list_channels().len(), 0);
2350 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2351 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2352 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2356 fn test_justice_tx() {
2357 // Test justice txn built on revoked HTLC-Success tx, against both sides
2358 let mut alice_config = UserConfig::default();
2359 alice_config.channel_options.announced_channel = true;
2360 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2361 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2362 let mut bob_config = UserConfig::default();
2363 bob_config.channel_options.announced_channel = true;
2364 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2365 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2366 let user_cfgs = [Some(alice_config), Some(bob_config)];
2367 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2368 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2369 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2370 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2371 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2372 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2373 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2374 // Create some new channels:
2375 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2377 // A pending HTLC which will be revoked:
2378 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2379 // Get the will-be-revoked local txn from nodes[0]
2380 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2381 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2382 assert_eq!(revoked_local_txn[0].input.len(), 1);
2383 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2384 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2385 assert_eq!(revoked_local_txn[1].input.len(), 1);
2386 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2387 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2388 // Revoke the old state
2389 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2392 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2394 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2395 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2396 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2398 check_spends!(node_txn[0], revoked_local_txn[0]);
2399 node_txn.swap_remove(0);
2400 node_txn.truncate(1);
2402 check_added_monitors!(nodes[1], 1);
2403 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2404 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2406 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2407 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2408 // Verify broadcast of revoked HTLC-timeout
2409 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2410 check_added_monitors!(nodes[0], 1);
2411 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2412 // Broadcast revoked HTLC-timeout on node 1
2413 mine_transaction(&nodes[1], &node_txn[1]);
2414 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2416 get_announce_close_broadcast_events(&nodes, 0, 1);
2418 assert_eq!(nodes[0].node.list_channels().len(), 0);
2419 assert_eq!(nodes[1].node.list_channels().len(), 0);
2421 // We test justice_tx build by A on B's revoked HTLC-Success tx
2422 // Create some new channels:
2423 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2425 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429 // A pending HTLC which will be revoked:
2430 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431 // Get the will-be-revoked local txn from B
2432 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2433 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2434 assert_eq!(revoked_local_txn[0].input.len(), 1);
2435 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2436 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2437 // Revoke the old state
2438 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2440 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2442 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2444 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2446 check_spends!(node_txn[0], revoked_local_txn[0]);
2447 node_txn.swap_remove(0);
2449 check_added_monitors!(nodes[0], 1);
2450 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2452 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2453 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2454 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2455 check_added_monitors!(nodes[1], 1);
2456 mine_transaction(&nodes[0], &node_txn[1]);
2457 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2458 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2460 get_announce_close_broadcast_events(&nodes, 0, 1);
2461 assert_eq!(nodes[0].node.list_channels().len(), 0);
2462 assert_eq!(nodes[1].node.list_channels().len(), 0);
2466 fn revoked_output_claim() {
2467 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2468 // transaction is broadcast by its counterparty
2469 let chanmon_cfgs = create_chanmon_cfgs(2);
2470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2472 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2473 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2474 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2475 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2476 assert_eq!(revoked_local_txn.len(), 1);
2477 // Only output is the full channel value back to nodes[0]:
2478 assert_eq!(revoked_local_txn[0].output.len(), 1);
2479 // Send a payment through, updating everyone's latest commitment txn
2480 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2482 // Inform nodes[1] that nodes[0] broadcast a stale tx
2483 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2484 check_added_monitors!(nodes[1], 1);
2485 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2486 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2487 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2489 check_spends!(node_txn[0], revoked_local_txn[0]);
2490 check_spends!(node_txn[1], chan_1.3);
2492 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2493 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2494 get_announce_close_broadcast_events(&nodes, 0, 1);
2495 check_added_monitors!(nodes[0], 1);
2496 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2500 fn claim_htlc_outputs_shared_tx() {
2501 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2502 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2503 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2506 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2508 // Create some new channel:
2509 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2511 // Rebalance the network to generate htlc in the two directions
2512 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2513 // 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
2514 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2515 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2517 // Get the will-be-revoked local txn from node[0]
2518 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2519 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2520 assert_eq!(revoked_local_txn[0].input.len(), 1);
2521 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2522 assert_eq!(revoked_local_txn[1].input.len(), 1);
2523 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2524 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2525 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2527 //Revoke the old state
2528 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2531 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2532 check_added_monitors!(nodes[0], 1);
2533 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2534 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2535 check_added_monitors!(nodes[1], 1);
2536 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2537 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2538 expect_payment_failed!(nodes[1], payment_hash_2, true);
2540 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2541 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2543 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2544 check_spends!(node_txn[0], revoked_local_txn[0]);
2546 let mut witness_lens = BTreeSet::new();
2547 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2548 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2549 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2550 assert_eq!(witness_lens.len(), 3);
2551 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2552 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2553 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2555 // Next nodes[1] broadcasts its current local tx state:
2556 assert_eq!(node_txn[1].input.len(), 1);
2557 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2559 get_announce_close_broadcast_events(&nodes, 0, 1);
2560 assert_eq!(nodes[0].node.list_channels().len(), 0);
2561 assert_eq!(nodes[1].node.list_channels().len(), 0);
2565 fn claim_htlc_outputs_single_tx() {
2566 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2567 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2568 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2571 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2573 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2575 // Rebalance the network to generate htlc in the two directions
2576 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2577 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2578 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2579 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2580 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2582 // Get the will-be-revoked local txn from node[0]
2583 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2585 //Revoke the old state
2586 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2589 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2590 check_added_monitors!(nodes[0], 1);
2591 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2592 check_added_monitors!(nodes[1], 1);
2593 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2594 let mut events = nodes[0].node.get_and_clear_pending_events();
2595 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2597 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2598 _ => panic!("Unexpected event"),
2601 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2602 expect_payment_failed!(nodes[1], payment_hash_2, true);
2604 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2605 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2607 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2608 assert_eq!(node_txn[0].input.len(), 1);
2609 check_spends!(node_txn[0], chan_1.3);
2610 assert_eq!(node_txn[1].input.len(), 1);
2611 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2612 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2613 check_spends!(node_txn[1], node_txn[0]);
2615 // Justice transactions are indices 1-2-4
2616 assert_eq!(node_txn[2].input.len(), 1);
2617 assert_eq!(node_txn[3].input.len(), 1);
2618 assert_eq!(node_txn[4].input.len(), 1);
2620 check_spends!(node_txn[2], revoked_local_txn[0]);
2621 check_spends!(node_txn[3], revoked_local_txn[0]);
2622 check_spends!(node_txn[4], revoked_local_txn[0]);
2624 let mut witness_lens = BTreeSet::new();
2625 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2626 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2627 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2628 assert_eq!(witness_lens.len(), 3);
2629 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2630 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2631 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2633 get_announce_close_broadcast_events(&nodes, 0, 1);
2634 assert_eq!(nodes[0].node.list_channels().len(), 0);
2635 assert_eq!(nodes[1].node.list_channels().len(), 0);
2639 fn test_htlc_on_chain_success() {
2640 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2641 // the preimage backward accordingly. So here we test that ChannelManager is
2642 // broadcasting the right event to other nodes in payment path.
2643 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2644 // A --------------------> B ----------------------> C (preimage)
2645 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2646 // commitment transaction was broadcast.
2647 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2649 // B should be able to claim via preimage if A then broadcasts its local tx.
2650 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2651 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2652 // PaymentSent event).
2654 let chanmon_cfgs = create_chanmon_cfgs(3);
2655 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2656 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2657 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2659 // Create some initial channels
2660 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2661 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2663 // Ensure all nodes are at the same height
2664 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2665 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2666 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2667 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2669 // Rebalance the network a bit by relaying one payment through all the channels...
2670 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2671 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2673 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2674 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2676 // Broadcast legit commitment tx from C on B's chain
2677 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2678 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2679 assert_eq!(commitment_tx.len(), 1);
2680 check_spends!(commitment_tx[0], chan_2.3);
2681 nodes[2].node.claim_funds(our_payment_preimage);
2682 nodes[2].node.claim_funds(our_payment_preimage_2);
2683 check_added_monitors!(nodes[2], 2);
2684 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2685 assert!(updates.update_add_htlcs.is_empty());
2686 assert!(updates.update_fail_htlcs.is_empty());
2687 assert!(updates.update_fail_malformed_htlcs.is_empty());
2688 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2690 mine_transaction(&nodes[2], &commitment_tx[0]);
2691 check_closed_broadcast!(nodes[2], true);
2692 check_added_monitors!(nodes[2], 1);
2693 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2694 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)
2695 assert_eq!(node_txn.len(), 5);
2696 assert_eq!(node_txn[0], node_txn[3]);
2697 assert_eq!(node_txn[1], node_txn[4]);
2698 assert_eq!(node_txn[2], commitment_tx[0]);
2699 check_spends!(node_txn[0], commitment_tx[0]);
2700 check_spends!(node_txn[1], commitment_tx[0]);
2701 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2702 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2703 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2704 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2705 assert_eq!(node_txn[0].lock_time, 0);
2706 assert_eq!(node_txn[1].lock_time, 0);
2708 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2709 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2710 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2711 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2713 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2714 assert_eq!(added_monitors.len(), 1);
2715 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2716 added_monitors.clear();
2718 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2719 assert_eq!(forwarded_events.len(), 3);
2720 match forwarded_events[0] {
2721 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2722 _ => panic!("Unexpected event"),
2724 let chan_id = Some(chan_1.2);
2725 match forwarded_events[1] {
2726 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2727 assert_eq!(fee_earned_msat, Some(1000));
2728 assert_eq!(source_channel_id, chan_id);
2729 assert_eq!(claim_from_onchain_tx, true);
2733 match forwarded_events[2] {
2734 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2735 assert_eq!(fee_earned_msat, Some(1000));
2736 assert_eq!(source_channel_id, chan_id);
2737 assert_eq!(claim_from_onchain_tx, true);
2741 let events = nodes[1].node.get_and_clear_pending_msg_events();
2743 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2744 assert_eq!(added_monitors.len(), 2);
2745 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2746 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2747 added_monitors.clear();
2749 assert_eq!(events.len(), 3);
2751 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2752 _ => panic!("Unexpected event"),
2755 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2756 _ => panic!("Unexpected event"),
2760 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, .. } } => {
2761 assert!(update_add_htlcs.is_empty());
2762 assert!(update_fail_htlcs.is_empty());
2763 assert_eq!(update_fulfill_htlcs.len(), 1);
2764 assert!(update_fail_malformed_htlcs.is_empty());
2765 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2767 _ => panic!("Unexpected event"),
2769 macro_rules! check_tx_local_broadcast {
2770 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2771 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2772 assert_eq!(node_txn.len(), 3);
2773 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2774 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2775 check_spends!(node_txn[1], $commitment_tx);
2776 check_spends!(node_txn[2], $commitment_tx);
2777 assert_ne!(node_txn[1].lock_time, 0);
2778 assert_ne!(node_txn[2].lock_time, 0);
2780 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2781 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2782 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2783 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2785 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2786 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2787 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2788 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2790 check_spends!(node_txn[0], $chan_tx);
2791 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2795 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2796 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2797 // timeout-claim of the output that nodes[2] just claimed via success.
2798 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2800 // Broadcast legit commitment tx from A on B's chain
2801 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2802 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2803 check_spends!(node_a_commitment_tx[0], chan_1.3);
2804 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2805 check_closed_broadcast!(nodes[1], true);
2806 check_added_monitors!(nodes[1], 1);
2807 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2808 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2809 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2810 let commitment_spend =
2811 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2812 check_spends!(node_txn[1], commitment_tx[0]);
2813 check_spends!(node_txn[2], commitment_tx[0]);
2814 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2817 check_spends!(node_txn[0], commitment_tx[0]);
2818 check_spends!(node_txn[1], commitment_tx[0]);
2819 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2823 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2824 assert_eq!(commitment_spend.input.len(), 2);
2825 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2826 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2827 assert_eq!(commitment_spend.lock_time, 0);
2828 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2829 check_spends!(node_txn[3], chan_1.3);
2830 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2831 check_spends!(node_txn[4], node_txn[3]);
2832 check_spends!(node_txn[5], node_txn[3]);
2833 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2834 // we already checked the same situation with A.
2836 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2837 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2838 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2839 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2840 check_closed_broadcast!(nodes[0], true);
2841 check_added_monitors!(nodes[0], 1);
2842 let events = nodes[0].node.get_and_clear_pending_events();
2843 assert_eq!(events.len(), 5);
2844 let mut first_claimed = false;
2845 for event in events {
2847 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2848 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2849 assert!(!first_claimed);
2850 first_claimed = true;
2852 assert_eq!(payment_preimage, our_payment_preimage_2);
2853 assert_eq!(payment_hash, payment_hash_2);
2856 Event::PaymentPathSuccessful { .. } => {},
2857 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2858 _ => panic!("Unexpected event"),
2861 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2864 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2865 // Test that in case of a unilateral close onchain, we detect the state of output and
2866 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2867 // broadcasting the right event to other nodes in payment path.
2868 // A ------------------> B ----------------------> C (timeout)
2869 // B's commitment tx C's commitment tx
2871 // B's HTLC timeout tx B's timeout tx
2873 let chanmon_cfgs = create_chanmon_cfgs(3);
2874 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2875 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2876 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2877 *nodes[0].connect_style.borrow_mut() = connect_style;
2878 *nodes[1].connect_style.borrow_mut() = connect_style;
2879 *nodes[2].connect_style.borrow_mut() = connect_style;
2881 // Create some intial channels
2882 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2883 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2885 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2886 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2887 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2889 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2891 // Broadcast legit commitment tx from C on B's chain
2892 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2893 check_spends!(commitment_tx[0], chan_2.3);
2894 nodes[2].node.fail_htlc_backwards(&payment_hash);
2895 check_added_monitors!(nodes[2], 0);
2896 expect_pending_htlcs_forwardable!(nodes[2]);
2897 check_added_monitors!(nodes[2], 1);
2899 let events = nodes[2].node.get_and_clear_pending_msg_events();
2900 assert_eq!(events.len(), 1);
2902 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, .. } } => {
2903 assert!(update_add_htlcs.is_empty());
2904 assert!(!update_fail_htlcs.is_empty());
2905 assert!(update_fulfill_htlcs.is_empty());
2906 assert!(update_fail_malformed_htlcs.is_empty());
2907 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2909 _ => panic!("Unexpected event"),
2911 mine_transaction(&nodes[2], &commitment_tx[0]);
2912 check_closed_broadcast!(nodes[2], true);
2913 check_added_monitors!(nodes[2], 1);
2914 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2915 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2916 assert_eq!(node_txn.len(), 1);
2917 check_spends!(node_txn[0], chan_2.3);
2918 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2920 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2921 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2922 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2923 mine_transaction(&nodes[1], &commitment_tx[0]);
2924 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2927 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2928 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2929 assert_eq!(node_txn[0], node_txn[3]);
2930 assert_eq!(node_txn[1], node_txn[4]);
2932 check_spends!(node_txn[2], commitment_tx[0]);
2933 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2935 check_spends!(node_txn[0], chan_2.3);
2936 check_spends!(node_txn[1], node_txn[0]);
2937 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2938 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2940 timeout_tx = node_txn[2].clone();
2944 mine_transaction(&nodes[1], &timeout_tx);
2945 check_added_monitors!(nodes[1], 1);
2946 check_closed_broadcast!(nodes[1], true);
2948 // B will rebroadcast a fee-bumped timeout transaction here.
2949 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2950 assert_eq!(node_txn.len(), 1);
2951 check_spends!(node_txn[0], commitment_tx[0]);
2954 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2956 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2957 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2958 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2959 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2960 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2961 if node_txn.len() == 1 {
2962 check_spends!(node_txn[0], chan_2.3);
2964 assert_eq!(node_txn.len(), 0);
2968 expect_pending_htlcs_forwardable!(nodes[1]);
2969 check_added_monitors!(nodes[1], 1);
2970 let events = nodes[1].node.get_and_clear_pending_msg_events();
2971 assert_eq!(events.len(), 1);
2973 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, .. } } => {
2974 assert!(update_add_htlcs.is_empty());
2975 assert!(!update_fail_htlcs.is_empty());
2976 assert!(update_fulfill_htlcs.is_empty());
2977 assert!(update_fail_malformed_htlcs.is_empty());
2978 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2980 _ => panic!("Unexpected event"),
2983 // Broadcast legit commitment tx from B on A's chain
2984 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2985 check_spends!(commitment_tx[0], chan_1.3);
2987 mine_transaction(&nodes[0], &commitment_tx[0]);
2988 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2990 check_closed_broadcast!(nodes[0], true);
2991 check_added_monitors!(nodes[0], 1);
2992 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2993 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2994 assert_eq!(node_txn.len(), 2);
2995 check_spends!(node_txn[0], chan_1.3);
2996 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2997 check_spends!(node_txn[1], commitment_tx[0]);
2998 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3002 fn test_htlc_on_chain_timeout() {
3003 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3004 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3005 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3009 fn test_simple_commitment_revoked_fail_backward() {
3010 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3011 // and fail backward accordingly.
3013 let chanmon_cfgs = create_chanmon_cfgs(3);
3014 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3015 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3016 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3018 // Create some initial channels
3019 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3020 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3022 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3023 // Get the will-be-revoked local txn from nodes[2]
3024 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3025 // Revoke the old state
3026 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3028 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3030 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3031 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3032 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3033 check_added_monitors!(nodes[1], 1);
3034 check_closed_broadcast!(nodes[1], true);
3036 expect_pending_htlcs_forwardable!(nodes[1]);
3037 check_added_monitors!(nodes[1], 1);
3038 let events = nodes[1].node.get_and_clear_pending_msg_events();
3039 assert_eq!(events.len(), 1);
3041 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, .. } } => {
3042 assert!(update_add_htlcs.is_empty());
3043 assert_eq!(update_fail_htlcs.len(), 1);
3044 assert!(update_fulfill_htlcs.is_empty());
3045 assert!(update_fail_malformed_htlcs.is_empty());
3046 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3048 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3049 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3050 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3052 _ => panic!("Unexpected event"),
3056 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3057 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3058 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3059 // commitment transaction anymore.
3060 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3061 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3062 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3063 // technically disallowed and we should probably handle it reasonably.
3064 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3065 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3067 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3068 // commitment_signed (implying it will be in the latest remote commitment transaction).
3069 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3070 // and once they revoke the previous commitment transaction (allowing us to send a new
3071 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3072 let chanmon_cfgs = create_chanmon_cfgs(3);
3073 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3074 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3075 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3077 // Create some initial channels
3078 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3079 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3081 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 });
3082 // Get the will-be-revoked local txn from nodes[2]
3083 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3084 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3085 // Revoke the old state
3086 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3088 let value = if use_dust {
3089 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3090 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3091 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3094 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3095 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3096 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3098 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3099 expect_pending_htlcs_forwardable!(nodes[2]);
3100 check_added_monitors!(nodes[2], 1);
3101 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3102 assert!(updates.update_add_htlcs.is_empty());
3103 assert!(updates.update_fulfill_htlcs.is_empty());
3104 assert!(updates.update_fail_malformed_htlcs.is_empty());
3105 assert_eq!(updates.update_fail_htlcs.len(), 1);
3106 assert!(updates.update_fee.is_none());
3107 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3108 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3109 // Drop the last RAA from 3 -> 2
3111 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3112 expect_pending_htlcs_forwardable!(nodes[2]);
3113 check_added_monitors!(nodes[2], 1);
3114 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3115 assert!(updates.update_add_htlcs.is_empty());
3116 assert!(updates.update_fulfill_htlcs.is_empty());
3117 assert!(updates.update_fail_malformed_htlcs.is_empty());
3118 assert_eq!(updates.update_fail_htlcs.len(), 1);
3119 assert!(updates.update_fee.is_none());
3120 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3121 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3122 check_added_monitors!(nodes[1], 1);
3123 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3124 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3125 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3126 check_added_monitors!(nodes[2], 1);
3128 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3129 expect_pending_htlcs_forwardable!(nodes[2]);
3130 check_added_monitors!(nodes[2], 1);
3131 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3132 assert!(updates.update_add_htlcs.is_empty());
3133 assert!(updates.update_fulfill_htlcs.is_empty());
3134 assert!(updates.update_fail_malformed_htlcs.is_empty());
3135 assert_eq!(updates.update_fail_htlcs.len(), 1);
3136 assert!(updates.update_fee.is_none());
3137 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3138 // At this point first_payment_hash has dropped out of the latest two commitment
3139 // transactions that nodes[1] is tracking...
3140 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3141 check_added_monitors!(nodes[1], 1);
3142 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3143 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3144 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3145 check_added_monitors!(nodes[2], 1);
3147 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3148 // on nodes[2]'s RAA.
3149 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3150 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3151 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3152 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3153 check_added_monitors!(nodes[1], 0);
3156 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3157 // One monitor for the new revocation preimage, no second on as we won't generate a new
3158 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3159 check_added_monitors!(nodes[1], 1);
3160 let events = nodes[1].node.get_and_clear_pending_events();
3161 assert_eq!(events.len(), 1);
3163 Event::PendingHTLCsForwardable { .. } => { },
3164 _ => panic!("Unexpected event"),
3166 // Deliberately don't process the pending fail-back so they all fail back at once after
3167 // block connection just like the !deliver_bs_raa case
3170 let mut failed_htlcs = HashSet::new();
3171 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3173 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3174 check_added_monitors!(nodes[1], 1);
3175 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3176 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3178 let events = nodes[1].node.get_and_clear_pending_events();
3179 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3181 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3182 _ => panic!("Unexepected event"),
3185 Event::PaymentPathFailed { ref payment_hash, .. } => {
3186 assert_eq!(*payment_hash, fourth_payment_hash);
3188 _ => panic!("Unexpected event"),
3190 if !deliver_bs_raa {
3192 Event::PaymentFailed { ref payment_hash, .. } => {
3193 assert_eq!(*payment_hash, fourth_payment_hash);
3195 _ => panic!("Unexpected event"),
3198 Event::PendingHTLCsForwardable { .. } => { },
3199 _ => panic!("Unexpected event"),
3202 nodes[1].node.process_pending_htlc_forwards();
3203 check_added_monitors!(nodes[1], 1);
3205 let events = nodes[1].node.get_and_clear_pending_msg_events();
3206 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3207 match events[if deliver_bs_raa { 1 } else { 0 }] {
3208 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3209 _ => panic!("Unexpected event"),
3211 match events[if deliver_bs_raa { 2 } else { 1 }] {
3212 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3213 assert_eq!(channel_id, chan_2.2);
3214 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3216 _ => panic!("Unexpected event"),
3220 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, .. } } => {
3221 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3222 assert_eq!(update_add_htlcs.len(), 1);
3223 assert!(update_fulfill_htlcs.is_empty());
3224 assert!(update_fail_htlcs.is_empty());
3225 assert!(update_fail_malformed_htlcs.is_empty());
3227 _ => panic!("Unexpected event"),
3230 match events[if deliver_bs_raa { 3 } else { 2 }] {
3231 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3232 assert!(update_add_htlcs.is_empty());
3233 assert_eq!(update_fail_htlcs.len(), 3);
3234 assert!(update_fulfill_htlcs.is_empty());
3235 assert!(update_fail_malformed_htlcs.is_empty());
3236 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3238 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3239 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3240 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3242 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3244 let events = nodes[0].node.get_and_clear_pending_events();
3245 assert_eq!(events.len(), 3);
3247 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3248 assert!(failed_htlcs.insert(payment_hash.0));
3249 // If we delivered B's RAA we got an unknown preimage error, not something
3250 // that we should update our routing table for.
3251 if !deliver_bs_raa {
3252 assert!(network_update.is_some());
3255 _ => panic!("Unexpected event"),
3258 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3259 assert!(failed_htlcs.insert(payment_hash.0));
3260 assert!(network_update.is_some());
3262 _ => panic!("Unexpected event"),
3265 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3266 assert!(failed_htlcs.insert(payment_hash.0));
3267 assert!(network_update.is_some());
3269 _ => panic!("Unexpected event"),
3272 _ => panic!("Unexpected event"),
3275 assert!(failed_htlcs.contains(&first_payment_hash.0));
3276 assert!(failed_htlcs.contains(&second_payment_hash.0));
3277 assert!(failed_htlcs.contains(&third_payment_hash.0));
3281 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3282 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3283 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3284 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3285 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3289 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3290 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3291 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3292 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3293 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3297 fn fail_backward_pending_htlc_upon_channel_failure() {
3298 let chanmon_cfgs = create_chanmon_cfgs(2);
3299 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3300 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3301 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3302 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3304 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3306 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3307 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3308 check_added_monitors!(nodes[0], 1);
3310 let payment_event = {
3311 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3312 assert_eq!(events.len(), 1);
3313 SendEvent::from_event(events.remove(0))
3315 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3316 assert_eq!(payment_event.msgs.len(), 1);
3319 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3320 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3322 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3323 check_added_monitors!(nodes[0], 0);
3325 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3328 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3330 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3332 let secp_ctx = Secp256k1::new();
3333 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3334 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3335 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3336 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3337 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3339 // Send a 0-msat update_add_htlc to fail the channel.
3340 let update_add_htlc = msgs::UpdateAddHTLC {
3346 onion_routing_packet,
3348 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3350 let events = nodes[0].node.get_and_clear_pending_events();
3351 assert_eq!(events.len(), 2);
3352 // Check that Alice fails backward the pending HTLC from the second payment.
3354 Event::PaymentPathFailed { payment_hash, .. } => {
3355 assert_eq!(payment_hash, failed_payment_hash);
3357 _ => panic!("Unexpected event"),
3360 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3361 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3363 _ => panic!("Unexpected event {:?}", events[1]),
3365 check_closed_broadcast!(nodes[0], true);
3366 check_added_monitors!(nodes[0], 1);
3370 fn test_htlc_ignore_latest_remote_commitment() {
3371 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3372 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3373 let chanmon_cfgs = create_chanmon_cfgs(2);
3374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3376 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3377 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3379 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3380 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3381 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3382 check_closed_broadcast!(nodes[0], true);
3383 check_added_monitors!(nodes[0], 1);
3384 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3386 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3387 assert_eq!(node_txn.len(), 3);
3388 assert_eq!(node_txn[0], node_txn[1]);
3390 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3391 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3392 check_closed_broadcast!(nodes[1], true);
3393 check_added_monitors!(nodes[1], 1);
3394 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3396 // Duplicate the connect_block call since this may happen due to other listeners
3397 // registering new transactions
3398 header.prev_blockhash = header.block_hash();
3399 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3403 fn test_force_close_fail_back() {
3404 // Check which HTLCs are failed-backwards on channel force-closure
3405 let chanmon_cfgs = create_chanmon_cfgs(3);
3406 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3407 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3408 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3409 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3410 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3412 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3414 let mut payment_event = {
3415 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3416 check_added_monitors!(nodes[0], 1);
3418 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3419 assert_eq!(events.len(), 1);
3420 SendEvent::from_event(events.remove(0))
3423 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3424 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3426 expect_pending_htlcs_forwardable!(nodes[1]);
3428 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3429 assert_eq!(events_2.len(), 1);
3430 payment_event = SendEvent::from_event(events_2.remove(0));
3431 assert_eq!(payment_event.msgs.len(), 1);
3433 check_added_monitors!(nodes[1], 1);
3434 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3435 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3436 check_added_monitors!(nodes[2], 1);
3437 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3439 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3440 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3441 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3443 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3444 check_closed_broadcast!(nodes[2], true);
3445 check_added_monitors!(nodes[2], 1);
3446 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3448 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3449 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3450 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3451 // back to nodes[1] upon timeout otherwise.
3452 assert_eq!(node_txn.len(), 1);
3456 mine_transaction(&nodes[1], &tx);
3458 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3459 check_closed_broadcast!(nodes[1], true);
3460 check_added_monitors!(nodes[1], 1);
3461 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3463 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3465 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3466 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3468 mine_transaction(&nodes[2], &tx);
3469 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3470 assert_eq!(node_txn.len(), 1);
3471 assert_eq!(node_txn[0].input.len(), 1);
3472 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3473 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3474 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3476 check_spends!(node_txn[0], tx);
3480 fn test_dup_events_on_peer_disconnect() {
3481 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3482 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3483 // as we used to generate the event immediately upon receipt of the payment preimage in the
3484 // update_fulfill_htlc message.
3486 let chanmon_cfgs = create_chanmon_cfgs(2);
3487 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3488 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3489 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3490 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3492 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3494 assert!(nodes[1].node.claim_funds(payment_preimage));
3495 check_added_monitors!(nodes[1], 1);
3496 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3497 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3498 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3500 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3501 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3503 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3504 expect_payment_path_successful!(nodes[0]);
3508 fn test_peer_disconnected_before_funding_broadcasted() {
3509 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3510 // before the funding transaction has been broadcasted.
3511 let chanmon_cfgs = create_chanmon_cfgs(2);
3512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3516 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3517 // broadcasted, even though it's created by `nodes[0]`.
3518 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();
3519 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3520 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3521 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3522 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3524 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], 1_000_000, 42);
3525 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3527 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).is_ok());
3529 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3530 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3532 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3533 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3536 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3539 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3540 // disconnected before the funding transaction was broadcasted.
3541 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3542 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3544 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3545 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3549 fn test_simple_peer_disconnect() {
3550 // Test that we can reconnect when there are no lost messages
3551 let chanmon_cfgs = create_chanmon_cfgs(3);
3552 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3553 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3554 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3555 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3556 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3558 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3559 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3560 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3562 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3563 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3564 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3565 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3567 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3568 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3569 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3571 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3572 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3573 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3574 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3576 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3577 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3579 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3580 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3582 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3584 let events = nodes[0].node.get_and_clear_pending_events();
3585 assert_eq!(events.len(), 3);
3587 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3588 assert_eq!(payment_preimage, payment_preimage_3);
3589 assert_eq!(payment_hash, payment_hash_3);
3591 _ => panic!("Unexpected event"),
3594 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3595 assert_eq!(payment_hash, payment_hash_5);
3596 assert!(rejected_by_dest);
3598 _ => panic!("Unexpected event"),
3601 Event::PaymentPathSuccessful { .. } => {},
3602 _ => panic!("Unexpected event"),
3606 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3607 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3610 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3611 // Test that we can reconnect when in-flight HTLC updates get dropped
3612 let chanmon_cfgs = create_chanmon_cfgs(2);
3613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3615 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3617 let mut as_funding_locked = None;
3618 if messages_delivered == 0 {
3619 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3620 as_funding_locked = Some(funding_locked);
3621 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3622 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3623 // it before the channel_reestablish message.
3625 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3628 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3630 let payment_event = {
3631 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3632 check_added_monitors!(nodes[0], 1);
3634 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3635 assert_eq!(events.len(), 1);
3636 SendEvent::from_event(events.remove(0))
3638 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3640 if messages_delivered < 2 {
3641 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3643 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3644 if messages_delivered >= 3 {
3645 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3646 check_added_monitors!(nodes[1], 1);
3647 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3649 if messages_delivered >= 4 {
3650 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3651 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3652 check_added_monitors!(nodes[0], 1);
3654 if messages_delivered >= 5 {
3655 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3656 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3657 // No commitment_signed so get_event_msg's assert(len == 1) passes
3658 check_added_monitors!(nodes[0], 1);
3660 if messages_delivered >= 6 {
3661 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3662 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3663 check_added_monitors!(nodes[1], 1);
3670 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3671 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3672 if messages_delivered < 3 {
3673 if simulate_broken_lnd {
3674 // lnd has a long-standing bug where they send a funding_locked prior to a
3675 // channel_reestablish if you reconnect prior to funding_locked time.
3677 // Here we simulate that behavior, delivering a funding_locked immediately on
3678 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3679 // in `reconnect_nodes` but we currently don't fail based on that.
3681 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3682 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3684 // Even if the funding_locked messages get exchanged, as long as nothing further was
3685 // received on either side, both sides will need to resend them.
3686 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3687 } else if messages_delivered == 3 {
3688 // nodes[0] still wants its RAA + commitment_signed
3689 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3690 } else if messages_delivered == 4 {
3691 // nodes[0] still wants its commitment_signed
3692 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3693 } else if messages_delivered == 5 {
3694 // nodes[1] still wants its final RAA
3695 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3696 } else if messages_delivered == 6 {
3697 // Everything was delivered...
3698 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701 let events_1 = nodes[1].node.get_and_clear_pending_events();
3702 assert_eq!(events_1.len(), 1);
3704 Event::PendingHTLCsForwardable { .. } => { },
3705 _ => panic!("Unexpected event"),
3708 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3709 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3710 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3712 nodes[1].node.process_pending_htlc_forwards();
3714 let events_2 = nodes[1].node.get_and_clear_pending_events();
3715 assert_eq!(events_2.len(), 1);
3717 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3718 assert_eq!(payment_hash_1, *payment_hash);
3719 assert_eq!(amt, 1000000);
3721 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3722 assert!(payment_preimage.is_none());
3723 assert_eq!(payment_secret_1, *payment_secret);
3725 _ => panic!("expected PaymentPurpose::InvoicePayment")
3728 _ => panic!("Unexpected event"),
3731 nodes[1].node.claim_funds(payment_preimage_1);
3732 check_added_monitors!(nodes[1], 1);
3734 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3735 assert_eq!(events_3.len(), 1);
3736 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3737 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3738 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3739 assert!(updates.update_add_htlcs.is_empty());
3740 assert!(updates.update_fail_htlcs.is_empty());
3741 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3742 assert!(updates.update_fail_malformed_htlcs.is_empty());
3743 assert!(updates.update_fee.is_none());
3744 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3746 _ => panic!("Unexpected event"),
3749 if messages_delivered >= 1 {
3750 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3752 let events_4 = nodes[0].node.get_and_clear_pending_events();
3753 assert_eq!(events_4.len(), 1);
3755 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3756 assert_eq!(payment_preimage_1, *payment_preimage);
3757 assert_eq!(payment_hash_1, *payment_hash);
3759 _ => panic!("Unexpected event"),
3762 if messages_delivered >= 2 {
3763 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3764 check_added_monitors!(nodes[0], 1);
3765 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3767 if messages_delivered >= 3 {
3768 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3769 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3770 check_added_monitors!(nodes[1], 1);
3772 if messages_delivered >= 4 {
3773 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3774 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3775 // No commitment_signed so get_event_msg's assert(len == 1) passes
3776 check_added_monitors!(nodes[1], 1);
3778 if messages_delivered >= 5 {
3779 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3780 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3781 check_added_monitors!(nodes[0], 1);
3788 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3789 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3790 if messages_delivered < 2 {
3791 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3792 if messages_delivered < 1 {
3793 expect_payment_sent!(nodes[0], payment_preimage_1);
3795 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3797 } else if messages_delivered == 2 {
3798 // nodes[0] still wants its RAA + commitment_signed
3799 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3800 } else if messages_delivered == 3 {
3801 // nodes[0] still wants its commitment_signed
3802 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3803 } else if messages_delivered == 4 {
3804 // nodes[1] still wants its final RAA
3805 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3806 } else if messages_delivered == 5 {
3807 // Everything was delivered...
3808 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3811 if messages_delivered == 1 || messages_delivered == 2 {
3812 expect_payment_path_successful!(nodes[0]);
3815 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3816 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3817 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3819 if messages_delivered > 2 {
3820 expect_payment_path_successful!(nodes[0]);
3823 // Channel should still work fine...
3824 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3825 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3826 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3830 fn test_drop_messages_peer_disconnect_a() {
3831 do_test_drop_messages_peer_disconnect(0, true);
3832 do_test_drop_messages_peer_disconnect(0, false);
3833 do_test_drop_messages_peer_disconnect(1, false);
3834 do_test_drop_messages_peer_disconnect(2, false);
3838 fn test_drop_messages_peer_disconnect_b() {
3839 do_test_drop_messages_peer_disconnect(3, false);
3840 do_test_drop_messages_peer_disconnect(4, false);
3841 do_test_drop_messages_peer_disconnect(5, false);
3842 do_test_drop_messages_peer_disconnect(6, false);
3846 fn test_funding_peer_disconnect() {
3847 // Test that we can lock in our funding tx while disconnected
3848 let chanmon_cfgs = create_chanmon_cfgs(2);
3849 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3850 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3851 let persister: test_utils::TestPersister;
3852 let new_chain_monitor: test_utils::TestChainMonitor;
3853 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3854 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3855 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3857 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3858 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3860 confirm_transaction(&nodes[0], &tx);
3861 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3862 assert!(events_1.is_empty());
3864 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3866 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3867 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3869 confirm_transaction(&nodes[1], &tx);
3870 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3871 assert!(events_2.is_empty());
3873 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3874 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3875 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3876 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3878 // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3879 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3880 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3881 assert_eq!(events_3.len(), 1);
3882 let as_funding_locked = match events_3[0] {
3883 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3884 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3887 _ => panic!("Unexpected event {:?}", events_3[0]),
3890 // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3891 // announcement_signatures as well as channel_update.
3892 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3893 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3894 assert_eq!(events_4.len(), 3);
3896 let bs_funding_locked = match events_4[0] {
3897 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3898 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3899 chan_id = msg.channel_id;
3902 _ => panic!("Unexpected event {:?}", events_4[0]),
3904 let bs_announcement_sigs = match events_4[1] {
3905 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3906 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3909 _ => panic!("Unexpected event {:?}", events_4[1]),
3912 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3913 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3915 _ => panic!("Unexpected event {:?}", events_4[2]),
3918 // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3919 // generates a duplicative private channel_update
3920 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3921 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3922 assert_eq!(events_5.len(), 1);
3924 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3925 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3927 _ => panic!("Unexpected event {:?}", events_5[0]),
3930 // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3931 // announcement_signatures.
3932 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3933 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3934 assert_eq!(events_6.len(), 1);
3935 let as_announcement_sigs = match events_6[0] {
3936 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3937 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3940 _ => panic!("Unexpected event {:?}", events_6[0]),
3943 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3944 // broadcast the channel announcement globally, as well as re-send its (now-public)
3946 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3947 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3948 assert_eq!(events_7.len(), 1);
3949 let (chan_announcement, as_update) = match events_7[0] {
3950 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3951 (msg.clone(), update_msg.clone())
3953 _ => panic!("Unexpected event {:?}", events_7[0]),
3956 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3957 // same channel_announcement.
3958 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3959 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3960 assert_eq!(events_8.len(), 1);
3961 let bs_update = match events_8[0] {
3962 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3963 assert_eq!(*msg, chan_announcement);
3966 _ => panic!("Unexpected event {:?}", events_8[0]),
3969 // Provide the channel announcement and public updates to the network graph
3970 nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3971 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3972 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3974 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3975 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3976 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3978 // Check that after deserialization and reconnection we can still generate an identical
3979 // channel_announcement from the cached signatures.
3980 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3982 let nodes_0_serialized = nodes[0].node.encode();
3983 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3984 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3986 persister = test_utils::TestPersister::new();
3987 let keys_manager = &chanmon_cfgs[0].keys_manager;
3988 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);
3989 nodes[0].chain_monitor = &new_chain_monitor;
3990 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3991 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3992 &mut chan_0_monitor_read, keys_manager).unwrap();
3993 assert!(chan_0_monitor_read.is_empty());
3995 let mut nodes_0_read = &nodes_0_serialized[..];
3996 let (_, nodes_0_deserialized_tmp) = {
3997 let mut channel_monitors = HashMap::new();
3998 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3999 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4000 default_config: UserConfig::default(),
4002 fee_estimator: node_cfgs[0].fee_estimator,
4003 chain_monitor: nodes[0].chain_monitor,
4004 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4005 logger: nodes[0].logger,
4009 nodes_0_deserialized = nodes_0_deserialized_tmp;
4010 assert!(nodes_0_read.is_empty());
4012 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4013 nodes[0].node = &nodes_0_deserialized;
4014 check_added_monitors!(nodes[0], 1);
4016 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4018 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4019 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4020 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4021 let mut found_announcement = false;
4022 for event in msgs.iter() {
4024 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4025 if *msg == chan_announcement { found_announcement = true; }
4027 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4028 _ => panic!("Unexpected event"),
4031 assert!(found_announcement);
4035 fn test_funding_locked_without_best_block_updated() {
4036 // Previously, if we were offline when a funding transaction was locked in, and then we came
4037 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4038 // generate a funding_locked until a later best_block_updated. This tests that we generate the
4039 // funding_locked immediately instead.
4040 let chanmon_cfgs = create_chanmon_cfgs(2);
4041 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4042 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4043 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4044 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4046 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4048 let conf_height = nodes[0].best_block_info().1 + 1;
4049 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4050 let block_txn = [funding_tx];
4051 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4052 let conf_block_header = nodes[0].get_block_header(conf_height);
4053 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4055 // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
4056 let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
4057 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
4061 fn test_drop_messages_peer_disconnect_dual_htlc() {
4062 // Test that we can handle reconnecting when both sides of a channel have pending
4063 // commitment_updates when we disconnect.
4064 let chanmon_cfgs = create_chanmon_cfgs(2);
4065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4067 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4068 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4070 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4072 // Now try to send a second payment which will fail to send
4073 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4074 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4075 check_added_monitors!(nodes[0], 1);
4077 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4078 assert_eq!(events_1.len(), 1);
4080 MessageSendEvent::UpdateHTLCs { .. } => {},
4081 _ => panic!("Unexpected event"),
4084 assert!(nodes[1].node.claim_funds(payment_preimage_1));
4085 check_added_monitors!(nodes[1], 1);
4087 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4088 assert_eq!(events_2.len(), 1);
4090 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 } } => {
4091 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4092 assert!(update_add_htlcs.is_empty());
4093 assert_eq!(update_fulfill_htlcs.len(), 1);
4094 assert!(update_fail_htlcs.is_empty());
4095 assert!(update_fail_malformed_htlcs.is_empty());
4096 assert!(update_fee.is_none());
4098 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4099 let events_3 = nodes[0].node.get_and_clear_pending_events();
4100 assert_eq!(events_3.len(), 1);
4102 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4103 assert_eq!(*payment_preimage, payment_preimage_1);
4104 assert_eq!(*payment_hash, payment_hash_1);
4106 _ => panic!("Unexpected event"),
4109 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4110 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4111 // No commitment_signed so get_event_msg's assert(len == 1) passes
4112 check_added_monitors!(nodes[0], 1);
4114 _ => panic!("Unexpected event"),
4117 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4118 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4120 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4121 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4122 assert_eq!(reestablish_1.len(), 1);
4123 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4124 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4125 assert_eq!(reestablish_2.len(), 1);
4127 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4128 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4129 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4130 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4132 assert!(as_resp.0.is_none());
4133 assert!(bs_resp.0.is_none());
4135 assert!(bs_resp.1.is_none());
4136 assert!(bs_resp.2.is_none());
4138 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4140 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4141 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4142 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4143 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4144 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4146 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4147 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4148 // No commitment_signed so get_event_msg's assert(len == 1) passes
4149 check_added_monitors!(nodes[1], 1);
4151 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4152 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4153 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4154 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4155 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4156 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4157 assert!(bs_second_commitment_signed.update_fee.is_none());
4158 check_added_monitors!(nodes[1], 1);
4160 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4161 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4162 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4163 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4164 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4165 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4166 assert!(as_commitment_signed.update_fee.is_none());
4167 check_added_monitors!(nodes[0], 1);
4169 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4170 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4171 // No commitment_signed so get_event_msg's assert(len == 1) passes
4172 check_added_monitors!(nodes[0], 1);
4174 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4175 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4176 // No commitment_signed so get_event_msg's assert(len == 1) passes
4177 check_added_monitors!(nodes[1], 1);
4179 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4180 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4181 check_added_monitors!(nodes[1], 1);
4183 expect_pending_htlcs_forwardable!(nodes[1]);
4185 let events_5 = nodes[1].node.get_and_clear_pending_events();
4186 assert_eq!(events_5.len(), 1);
4188 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4189 assert_eq!(payment_hash_2, *payment_hash);
4191 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4192 assert!(payment_preimage.is_none());
4193 assert_eq!(payment_secret_2, *payment_secret);
4195 _ => panic!("expected PaymentPurpose::InvoicePayment")
4198 _ => panic!("Unexpected event"),
4201 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4202 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4203 check_added_monitors!(nodes[0], 1);
4205 expect_payment_path_successful!(nodes[0]);
4206 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4209 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4210 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4211 // to avoid our counterparty failing the channel.
4212 let chanmon_cfgs = create_chanmon_cfgs(2);
4213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4215 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4217 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4219 let our_payment_hash = if send_partial_mpp {
4220 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4221 // Use the utility function send_payment_along_path to send the payment with MPP data which
4222 // indicates there are more HTLCs coming.
4223 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.
4224 let payment_id = PaymentId([42; 32]);
4225 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();
4226 check_added_monitors!(nodes[0], 1);
4227 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4228 assert_eq!(events.len(), 1);
4229 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4230 // hop should *not* yet generate any PaymentReceived event(s).
4231 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4234 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4237 let mut block = Block {
4238 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4241 connect_block(&nodes[0], &block);
4242 connect_block(&nodes[1], &block);
4243 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4244 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4245 block.header.prev_blockhash = block.block_hash();
4246 connect_block(&nodes[0], &block);
4247 connect_block(&nodes[1], &block);
4250 expect_pending_htlcs_forwardable!(nodes[1]);
4252 check_added_monitors!(nodes[1], 1);
4253 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4254 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4255 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4256 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4257 assert!(htlc_timeout_updates.update_fee.is_none());
4259 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4260 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4261 // 100_000 msat as u64, followed by the height at which we failed back above
4262 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4263 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4264 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4268 fn test_htlc_timeout() {
4269 do_test_htlc_timeout(true);
4270 do_test_htlc_timeout(false);
4273 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4274 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4275 let chanmon_cfgs = create_chanmon_cfgs(3);
4276 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4277 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4278 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4279 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4280 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4282 // Make sure all nodes are at the same starting height
4283 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4284 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4285 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4287 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4288 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4290 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4292 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4293 check_added_monitors!(nodes[1], 1);
4295 // Now attempt to route a second payment, which should be placed in the holding cell
4296 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4297 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4298 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4300 check_added_monitors!(nodes[0], 1);
4301 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4303 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4304 expect_pending_htlcs_forwardable!(nodes[1]);
4306 check_added_monitors!(nodes[1], 0);
4308 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4309 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4310 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4311 connect_blocks(&nodes[1], 1);
4314 expect_pending_htlcs_forwardable!(nodes[1]);
4315 check_added_monitors!(nodes[1], 1);
4316 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4317 assert_eq!(fail_commit.len(), 1);
4318 match fail_commit[0] {
4319 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4320 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4321 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4323 _ => unreachable!(),
4325 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4327 let events = nodes[1].node.get_and_clear_pending_events();
4328 assert_eq!(events.len(), 2);
4329 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4330 assert_eq!(*payment_hash, second_payment_hash);
4331 } else { panic!("Unexpected event"); }
4332 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4333 assert_eq!(*payment_hash, second_payment_hash);
4334 } else { panic!("Unexpected event"); }
4339 fn test_holding_cell_htlc_add_timeouts() {
4340 do_test_holding_cell_htlc_add_timeouts(false);
4341 do_test_holding_cell_htlc_add_timeouts(true);
4345 fn test_no_txn_manager_serialize_deserialize() {
4346 let chanmon_cfgs = create_chanmon_cfgs(2);
4347 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4348 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4349 let logger: test_utils::TestLogger;
4350 let fee_estimator: test_utils::TestFeeEstimator;
4351 let persister: test_utils::TestPersister;
4352 let new_chain_monitor: test_utils::TestChainMonitor;
4353 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4354 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4356 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4358 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4360 let nodes_0_serialized = nodes[0].node.encode();
4361 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4362 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4363 .write(&mut chan_0_monitor_serialized).unwrap();
4365 logger = test_utils::TestLogger::new();
4366 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4367 persister = test_utils::TestPersister::new();
4368 let keys_manager = &chanmon_cfgs[0].keys_manager;
4369 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4370 nodes[0].chain_monitor = &new_chain_monitor;
4371 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4372 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4373 &mut chan_0_monitor_read, keys_manager).unwrap();
4374 assert!(chan_0_monitor_read.is_empty());
4376 let mut nodes_0_read = &nodes_0_serialized[..];
4377 let config = UserConfig::default();
4378 let (_, nodes_0_deserialized_tmp) = {
4379 let mut channel_monitors = HashMap::new();
4380 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4381 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4382 default_config: config,
4384 fee_estimator: &fee_estimator,
4385 chain_monitor: nodes[0].chain_monitor,
4386 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4391 nodes_0_deserialized = nodes_0_deserialized_tmp;
4392 assert!(nodes_0_read.is_empty());
4394 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4395 nodes[0].node = &nodes_0_deserialized;
4396 assert_eq!(nodes[0].node.list_channels().len(), 1);
4397 check_added_monitors!(nodes[0], 1);
4399 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4400 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4401 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4402 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4404 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4405 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4406 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4407 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4409 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4410 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4411 for node in nodes.iter() {
4412 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4413 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4414 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4417 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4421 fn test_manager_serialize_deserialize_events() {
4422 // This test makes sure the events field in ChannelManager survives de/serialization
4423 let chanmon_cfgs = create_chanmon_cfgs(2);
4424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4426 let fee_estimator: test_utils::TestFeeEstimator;
4427 let persister: test_utils::TestPersister;
4428 let logger: test_utils::TestLogger;
4429 let new_chain_monitor: test_utils::TestChainMonitor;
4430 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4431 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4433 // Start creating a channel, but stop right before broadcasting the funding transaction
4434 let channel_value = 100000;
4435 let push_msat = 10001;
4436 let a_flags = InitFeatures::known();
4437 let b_flags = InitFeatures::known();
4438 let node_a = nodes.remove(0);
4439 let node_b = nodes.remove(0);
4440 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4441 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()));
4442 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()));
4444 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4446 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4447 check_added_monitors!(node_a, 0);
4449 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()));
4451 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4452 assert_eq!(added_monitors.len(), 1);
4453 assert_eq!(added_monitors[0].0, funding_output);
4454 added_monitors.clear();
4457 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4458 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4460 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4461 assert_eq!(added_monitors.len(), 1);
4462 assert_eq!(added_monitors[0].0, funding_output);
4463 added_monitors.clear();
4465 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4470 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4471 let nodes_0_serialized = nodes[0].node.encode();
4472 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4473 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4475 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4476 logger = test_utils::TestLogger::new();
4477 persister = test_utils::TestPersister::new();
4478 let keys_manager = &chanmon_cfgs[0].keys_manager;
4479 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4480 nodes[0].chain_monitor = &new_chain_monitor;
4481 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4482 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4483 &mut chan_0_monitor_read, keys_manager).unwrap();
4484 assert!(chan_0_monitor_read.is_empty());
4486 let mut nodes_0_read = &nodes_0_serialized[..];
4487 let config = UserConfig::default();
4488 let (_, nodes_0_deserialized_tmp) = {
4489 let mut channel_monitors = HashMap::new();
4490 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4491 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4492 default_config: config,
4494 fee_estimator: &fee_estimator,
4495 chain_monitor: nodes[0].chain_monitor,
4496 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4501 nodes_0_deserialized = nodes_0_deserialized_tmp;
4502 assert!(nodes_0_read.is_empty());
4504 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4506 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4507 nodes[0].node = &nodes_0_deserialized;
4509 // After deserializing, make sure the funding_transaction is still held by the channel manager
4510 let events_4 = nodes[0].node.get_and_clear_pending_events();
4511 assert_eq!(events_4.len(), 0);
4512 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4513 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4515 // Make sure the channel is functioning as though the de/serialization never happened
4516 assert_eq!(nodes[0].node.list_channels().len(), 1);
4517 check_added_monitors!(nodes[0], 1);
4519 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4520 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4521 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4522 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4524 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4525 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4526 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4527 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4529 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4530 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4531 for node in nodes.iter() {
4532 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4533 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4534 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4537 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4541 fn test_simple_manager_serialize_deserialize() {
4542 let chanmon_cfgs = create_chanmon_cfgs(2);
4543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4545 let logger: test_utils::TestLogger;
4546 let fee_estimator: test_utils::TestFeeEstimator;
4547 let persister: test_utils::TestPersister;
4548 let new_chain_monitor: test_utils::TestChainMonitor;
4549 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4550 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4551 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4553 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4554 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4556 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4558 let nodes_0_serialized = nodes[0].node.encode();
4559 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4560 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4562 logger = test_utils::TestLogger::new();
4563 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4564 persister = test_utils::TestPersister::new();
4565 let keys_manager = &chanmon_cfgs[0].keys_manager;
4566 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4567 nodes[0].chain_monitor = &new_chain_monitor;
4568 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4569 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4570 &mut chan_0_monitor_read, keys_manager).unwrap();
4571 assert!(chan_0_monitor_read.is_empty());
4573 let mut nodes_0_read = &nodes_0_serialized[..];
4574 let (_, nodes_0_deserialized_tmp) = {
4575 let mut channel_monitors = HashMap::new();
4576 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4577 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4578 default_config: UserConfig::default(),
4580 fee_estimator: &fee_estimator,
4581 chain_monitor: nodes[0].chain_monitor,
4582 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4587 nodes_0_deserialized = nodes_0_deserialized_tmp;
4588 assert!(nodes_0_read.is_empty());
4590 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4591 nodes[0].node = &nodes_0_deserialized;
4592 check_added_monitors!(nodes[0], 1);
4594 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4596 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4597 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4601 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4602 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4603 let chanmon_cfgs = create_chanmon_cfgs(4);
4604 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4605 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4606 let logger: test_utils::TestLogger;
4607 let fee_estimator: test_utils::TestFeeEstimator;
4608 let persister: test_utils::TestPersister;
4609 let new_chain_monitor: test_utils::TestChainMonitor;
4610 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4611 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4612 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4613 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4614 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4616 let mut node_0_stale_monitors_serialized = Vec::new();
4617 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4618 let mut writer = test_utils::TestVecWriter(Vec::new());
4619 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4620 node_0_stale_monitors_serialized.push(writer.0);
4623 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4625 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4626 let nodes_0_serialized = nodes[0].node.encode();
4628 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4629 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4630 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4631 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4633 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4635 let mut node_0_monitors_serialized = Vec::new();
4636 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4637 let mut writer = test_utils::TestVecWriter(Vec::new());
4638 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4639 node_0_monitors_serialized.push(writer.0);
4642 logger = test_utils::TestLogger::new();
4643 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4644 persister = test_utils::TestPersister::new();
4645 let keys_manager = &chanmon_cfgs[0].keys_manager;
4646 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4647 nodes[0].chain_monitor = &new_chain_monitor;
4650 let mut node_0_stale_monitors = Vec::new();
4651 for serialized in node_0_stale_monitors_serialized.iter() {
4652 let mut read = &serialized[..];
4653 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4654 assert!(read.is_empty());
4655 node_0_stale_monitors.push(monitor);
4658 let mut node_0_monitors = Vec::new();
4659 for serialized in node_0_monitors_serialized.iter() {
4660 let mut read = &serialized[..];
4661 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4662 assert!(read.is_empty());
4663 node_0_monitors.push(monitor);
4666 let mut nodes_0_read = &nodes_0_serialized[..];
4667 if let Err(msgs::DecodeError::InvalidValue) =
4668 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4669 default_config: UserConfig::default(),
4671 fee_estimator: &fee_estimator,
4672 chain_monitor: nodes[0].chain_monitor,
4673 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4675 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4677 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4680 let mut nodes_0_read = &nodes_0_serialized[..];
4681 let (_, nodes_0_deserialized_tmp) =
4682 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4683 default_config: UserConfig::default(),
4685 fee_estimator: &fee_estimator,
4686 chain_monitor: nodes[0].chain_monitor,
4687 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4689 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4691 nodes_0_deserialized = nodes_0_deserialized_tmp;
4692 assert!(nodes_0_read.is_empty());
4694 { // Channel close should result in a commitment tx
4695 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4696 assert_eq!(txn.len(), 1);
4697 check_spends!(txn[0], funding_tx);
4698 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4701 for monitor in node_0_monitors.drain(..) {
4702 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4703 check_added_monitors!(nodes[0], 1);
4705 nodes[0].node = &nodes_0_deserialized;
4706 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4708 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4709 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4710 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4711 //... and we can even still claim the payment!
4712 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4714 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4715 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4716 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4717 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4718 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4719 assert_eq!(msg_events.len(), 1);
4720 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4722 &ErrorAction::SendErrorMessage { ref msg } => {
4723 assert_eq!(msg.channel_id, channel_id);
4725 _ => panic!("Unexpected event!"),
4730 macro_rules! check_spendable_outputs {
4731 ($node: expr, $keysinterface: expr) => {
4733 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4734 let mut txn = Vec::new();
4735 let mut all_outputs = Vec::new();
4736 let secp_ctx = Secp256k1::new();
4737 for event in events.drain(..) {
4739 Event::SpendableOutputs { mut outputs } => {
4740 for outp in outputs.drain(..) {
4741 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4742 all_outputs.push(outp);
4745 _ => panic!("Unexpected event"),
4748 if all_outputs.len() > 1 {
4749 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) {
4759 fn test_claim_sizeable_push_msat() {
4760 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4761 let chanmon_cfgs = create_chanmon_cfgs(2);
4762 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4763 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4764 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4766 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4767 nodes[1].node.force_close_channel(&chan.2).unwrap();
4768 check_closed_broadcast!(nodes[1], true);
4769 check_added_monitors!(nodes[1], 1);
4770 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4771 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4772 assert_eq!(node_txn.len(), 1);
4773 check_spends!(node_txn[0], chan.3);
4774 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
4776 mine_transaction(&nodes[1], &node_txn[0]);
4777 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4779 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4780 assert_eq!(spend_txn.len(), 1);
4781 assert_eq!(spend_txn[0].input.len(), 1);
4782 check_spends!(spend_txn[0], node_txn[0]);
4783 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4787 fn test_claim_on_remote_sizeable_push_msat() {
4788 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4789 // to_remote output is encumbered by a P2WPKH
4790 let chanmon_cfgs = create_chanmon_cfgs(2);
4791 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4792 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4793 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4795 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4796 nodes[0].node.force_close_channel(&chan.2).unwrap();
4797 check_closed_broadcast!(nodes[0], true);
4798 check_added_monitors!(nodes[0], 1);
4799 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4801 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4802 assert_eq!(node_txn.len(), 1);
4803 check_spends!(node_txn[0], chan.3);
4804 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
4806 mine_transaction(&nodes[1], &node_txn[0]);
4807 check_closed_broadcast!(nodes[1], true);
4808 check_added_monitors!(nodes[1], 1);
4809 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4810 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4812 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4813 assert_eq!(spend_txn.len(), 1);
4814 check_spends!(spend_txn[0], node_txn[0]);
4818 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4819 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4820 // to_remote output is encumbered by a P2WPKH
4822 let chanmon_cfgs = create_chanmon_cfgs(2);
4823 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4824 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4825 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4827 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4828 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4829 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4830 assert_eq!(revoked_local_txn[0].input.len(), 1);
4831 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4833 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4834 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4835 check_closed_broadcast!(nodes[1], true);
4836 check_added_monitors!(nodes[1], 1);
4837 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4839 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4840 mine_transaction(&nodes[1], &node_txn[0]);
4841 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4843 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4844 assert_eq!(spend_txn.len(), 3);
4845 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4846 check_spends!(spend_txn[1], node_txn[0]);
4847 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4851 fn test_static_spendable_outputs_preimage_tx() {
4852 let chanmon_cfgs = create_chanmon_cfgs(2);
4853 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4854 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4855 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4857 // Create some initial channels
4858 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4860 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4862 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4863 assert_eq!(commitment_tx[0].input.len(), 1);
4864 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4866 // Settle A's commitment tx on B's chain
4867 assert!(nodes[1].node.claim_funds(payment_preimage));
4868 check_added_monitors!(nodes[1], 1);
4869 mine_transaction(&nodes[1], &commitment_tx[0]);
4870 check_added_monitors!(nodes[1], 1);
4871 let events = nodes[1].node.get_and_clear_pending_msg_events();
4873 MessageSendEvent::UpdateHTLCs { .. } => {},
4874 _ => panic!("Unexpected event"),
4877 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4878 _ => panic!("Unexepected event"),
4881 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4882 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4883 assert_eq!(node_txn.len(), 3);
4884 check_spends!(node_txn[0], commitment_tx[0]);
4885 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4886 check_spends!(node_txn[1], chan_1.3);
4887 check_spends!(node_txn[2], node_txn[1]);
4889 mine_transaction(&nodes[1], &node_txn[0]);
4890 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4891 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4893 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4894 assert_eq!(spend_txn.len(), 1);
4895 check_spends!(spend_txn[0], node_txn[0]);
4899 fn test_static_spendable_outputs_timeout_tx() {
4900 let chanmon_cfgs = create_chanmon_cfgs(2);
4901 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4902 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4903 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4905 // Create some initial channels
4906 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4908 // Rebalance the network a bit by relaying one payment through all the channels ...
4909 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4911 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4913 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4914 assert_eq!(commitment_tx[0].input.len(), 1);
4915 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4917 // Settle A's commitment tx on B' chain
4918 mine_transaction(&nodes[1], &commitment_tx[0]);
4919 check_added_monitors!(nodes[1], 1);
4920 let events = nodes[1].node.get_and_clear_pending_msg_events();
4922 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4923 _ => panic!("Unexpected event"),
4925 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4927 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4928 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4929 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4930 check_spends!(node_txn[0], chan_1.3.clone());
4931 check_spends!(node_txn[1], commitment_tx[0].clone());
4932 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4934 mine_transaction(&nodes[1], &node_txn[1]);
4935 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4936 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4937 expect_payment_failed!(nodes[1], our_payment_hash, true);
4939 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4940 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4941 check_spends!(spend_txn[0], commitment_tx[0]);
4942 check_spends!(spend_txn[1], node_txn[1]);
4943 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4947 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4948 let chanmon_cfgs = create_chanmon_cfgs(2);
4949 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4950 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4951 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4953 // Create some initial channels
4954 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4956 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4957 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4958 assert_eq!(revoked_local_txn[0].input.len(), 1);
4959 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4961 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4963 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4964 check_closed_broadcast!(nodes[1], true);
4965 check_added_monitors!(nodes[1], 1);
4966 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4968 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4969 assert_eq!(node_txn.len(), 2);
4970 assert_eq!(node_txn[0].input.len(), 2);
4971 check_spends!(node_txn[0], revoked_local_txn[0]);
4973 mine_transaction(&nodes[1], &node_txn[0]);
4974 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4976 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4977 assert_eq!(spend_txn.len(), 1);
4978 check_spends!(spend_txn[0], node_txn[0]);
4982 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4983 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4984 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4985 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4986 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4987 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4989 // Create some initial channels
4990 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4992 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4993 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4994 assert_eq!(revoked_local_txn[0].input.len(), 1);
4995 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4997 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4999 // A will generate HTLC-Timeout from revoked commitment tx
5000 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5001 check_closed_broadcast!(nodes[0], true);
5002 check_added_monitors!(nodes[0], 1);
5003 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5004 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5006 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5007 assert_eq!(revoked_htlc_txn.len(), 2);
5008 check_spends!(revoked_htlc_txn[0], chan_1.3);
5009 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5010 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5011 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5012 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5014 // B will generate justice tx from A's revoked commitment/HTLC tx
5015 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5016 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5017 check_closed_broadcast!(nodes[1], true);
5018 check_added_monitors!(nodes[1], 1);
5019 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5021 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5022 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5023 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5024 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5025 // transactions next...
5026 assert_eq!(node_txn[0].input.len(), 3);
5027 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5029 assert_eq!(node_txn[1].input.len(), 2);
5030 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5031 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5032 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5034 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5035 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5038 assert_eq!(node_txn[2].input.len(), 1);
5039 check_spends!(node_txn[2], chan_1.3);
5041 mine_transaction(&nodes[1], &node_txn[1]);
5042 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5044 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5045 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5046 assert_eq!(spend_txn.len(), 1);
5047 assert_eq!(spend_txn[0].input.len(), 1);
5048 check_spends!(spend_txn[0], node_txn[1]);
5052 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5053 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5054 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5055 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5056 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5057 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5059 // Create some initial channels
5060 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5062 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5063 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5064 assert_eq!(revoked_local_txn[0].input.len(), 1);
5065 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5067 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5068 assert_eq!(revoked_local_txn[0].output.len(), 2);
5070 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5072 // B will generate HTLC-Success from revoked commitment tx
5073 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5074 check_closed_broadcast!(nodes[1], true);
5075 check_added_monitors!(nodes[1], 1);
5076 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5077 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5079 assert_eq!(revoked_htlc_txn.len(), 2);
5080 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5081 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5082 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5084 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5085 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5086 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5088 // A will generate justice tx from B's revoked commitment/HTLC tx
5089 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5090 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5091 check_closed_broadcast!(nodes[0], true);
5092 check_added_monitors!(nodes[0], 1);
5093 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5095 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5096 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5098 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5099 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5100 // transactions next...
5101 assert_eq!(node_txn[0].input.len(), 2);
5102 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5103 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5104 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5106 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5107 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5110 assert_eq!(node_txn[1].input.len(), 1);
5111 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5113 check_spends!(node_txn[2], chan_1.3);
5115 mine_transaction(&nodes[0], &node_txn[1]);
5116 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5118 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5119 // didn't try to generate any new transactions.
5121 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5122 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5123 assert_eq!(spend_txn.len(), 3);
5124 assert_eq!(spend_txn[0].input.len(), 1);
5125 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5126 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5127 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5128 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5132 fn test_onchain_to_onchain_claim() {
5133 // Test that in case of channel closure, we detect the state of output and claim HTLC
5134 // on downstream peer's remote commitment tx.
5135 // First, have C claim an HTLC against its own latest commitment transaction.
5136 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5138 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5141 let chanmon_cfgs = create_chanmon_cfgs(3);
5142 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5143 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5144 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5146 // Create some initial channels
5147 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5148 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5150 // Ensure all nodes are at the same height
5151 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5152 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5153 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5154 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5156 // Rebalance the network a bit by relaying one payment through all the channels ...
5157 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5158 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5160 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5161 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5162 check_spends!(commitment_tx[0], chan_2.3);
5163 nodes[2].node.claim_funds(payment_preimage);
5164 check_added_monitors!(nodes[2], 1);
5165 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5166 assert!(updates.update_add_htlcs.is_empty());
5167 assert!(updates.update_fail_htlcs.is_empty());
5168 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5169 assert!(updates.update_fail_malformed_htlcs.is_empty());
5171 mine_transaction(&nodes[2], &commitment_tx[0]);
5172 check_closed_broadcast!(nodes[2], true);
5173 check_added_monitors!(nodes[2], 1);
5174 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5176 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5177 assert_eq!(c_txn.len(), 3);
5178 assert_eq!(c_txn[0], c_txn[2]);
5179 assert_eq!(commitment_tx[0], c_txn[1]);
5180 check_spends!(c_txn[1], chan_2.3);
5181 check_spends!(c_txn[2], c_txn[1]);
5182 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5183 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5184 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5185 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5187 // 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
5188 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5189 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5190 check_added_monitors!(nodes[1], 1);
5191 let events = nodes[1].node.get_and_clear_pending_events();
5192 assert_eq!(events.len(), 2);
5194 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5195 _ => panic!("Unexpected event"),
5198 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
5199 assert_eq!(fee_earned_msat, Some(1000));
5200 assert_eq!(source_channel_id, Some(chan_1.2));
5201 assert_eq!(claim_from_onchain_tx, true);
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], &vec!(&nodes[1], &nodes[2])[..], 900000);
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 * 2-or-3, ChannelManager: local commitment tx
5302 assert!(node_txn.len() == 4 || node_txn.len() == 3);
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);
5308 if node_txn.len() > 3 {
5309 check_spends!(node_txn[2], commitment_txn[0]);
5310 assert_eq!(node_txn[2].input.len(), 1);
5311 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5313 check_spends!(node_txn[3], commitment_txn[0]);
5314 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5316 check_spends!(node_txn[2], commitment_txn[0]);
5317 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5320 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5321 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5322 if node_txn.len() > 3 {
5323 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5325 htlc_timeout_tx = node_txn[1].clone();
5328 nodes[2].node.claim_funds(our_payment_preimage);
5329 mine_transaction(&nodes[2], &commitment_txn[0]);
5330 check_added_monitors!(nodes[2], 2);
5331 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5332 let events = nodes[2].node.get_and_clear_pending_msg_events();
5334 MessageSendEvent::UpdateHTLCs { .. } => {},
5335 _ => panic!("Unexpected event"),
5338 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5339 _ => panic!("Unexepected event"),
5341 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5342 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)
5343 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5344 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5345 assert_eq!(htlc_success_txn[0].input.len(), 1);
5346 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5347 assert_eq!(htlc_success_txn[1].input.len(), 1);
5348 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5349 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5350 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5351 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5352 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5353 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5355 mine_transaction(&nodes[1], &htlc_timeout_tx);
5356 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5357 expect_pending_htlcs_forwardable!(nodes[1]);
5358 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5359 assert!(htlc_updates.update_add_htlcs.is_empty());
5360 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5361 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5362 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5363 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5364 check_added_monitors!(nodes[1], 1);
5366 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5367 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5369 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5371 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5373 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5374 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5375 // and nodes[2] fee) is rounded down and then claimed in full.
5376 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5377 expect_payment_forwarded!(nodes[1], nodes[0], Some(196*2), true);
5378 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5379 assert!(updates.update_add_htlcs.is_empty());
5380 assert!(updates.update_fail_htlcs.is_empty());
5381 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5382 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5383 assert!(updates.update_fail_malformed_htlcs.is_empty());
5384 check_added_monitors!(nodes[1], 1);
5386 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5387 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5389 let events = nodes[0].node.get_and_clear_pending_events();
5391 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5392 assert_eq!(*payment_preimage, our_payment_preimage);
5393 assert_eq!(*payment_hash, duplicate_payment_hash);
5395 _ => panic!("Unexpected event"),
5400 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5401 let chanmon_cfgs = create_chanmon_cfgs(2);
5402 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5403 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5404 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5406 // Create some initial channels
5407 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5409 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5410 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5411 assert_eq!(local_txn.len(), 1);
5412 assert_eq!(local_txn[0].input.len(), 1);
5413 check_spends!(local_txn[0], chan_1.3);
5415 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5416 nodes[1].node.claim_funds(payment_preimage);
5417 check_added_monitors!(nodes[1], 1);
5418 mine_transaction(&nodes[1], &local_txn[0]);
5419 check_added_monitors!(nodes[1], 1);
5420 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5421 let events = nodes[1].node.get_and_clear_pending_msg_events();
5423 MessageSendEvent::UpdateHTLCs { .. } => {},
5424 _ => panic!("Unexpected event"),
5427 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5428 _ => panic!("Unexepected event"),
5431 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5432 assert_eq!(node_txn.len(), 3);
5433 assert_eq!(node_txn[0], node_txn[2]);
5434 assert_eq!(node_txn[1], local_txn[0]);
5435 assert_eq!(node_txn[0].input.len(), 1);
5436 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5437 check_spends!(node_txn[0], local_txn[0]);
5441 mine_transaction(&nodes[1], &node_tx);
5442 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5444 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5445 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5446 assert_eq!(spend_txn.len(), 1);
5447 assert_eq!(spend_txn[0].input.len(), 1);
5448 check_spends!(spend_txn[0], node_tx);
5449 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5452 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5453 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5454 // unrevoked commitment transaction.
5455 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5456 // a remote RAA before they could be failed backwards (and combinations thereof).
5457 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5458 // use the same payment hashes.
5459 // Thus, we use a six-node network:
5464 // And test where C fails back to A/B when D announces its latest commitment transaction
5465 let chanmon_cfgs = create_chanmon_cfgs(6);
5466 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5467 // When this test was written, the default base fee floated based on the HTLC count.
5468 // It is now fixed, so we simply set the fee to the expected value here.
5469 let mut config = test_default_channel_config();
5470 config.channel_options.forwarding_fee_base_msat = 196;
5471 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5472 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5473 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5475 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5476 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5477 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5478 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5479 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5481 // Rebalance and check output sanity...
5482 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5483 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5484 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5486 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5488 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
5490 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
5491 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5493 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
5495 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
5497 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5499 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5500 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5502 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());
5504 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());
5507 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5509 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5510 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
5513 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
5515 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5516 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());
5518 // Double-check that six of the new HTLC were added
5519 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5520 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5521 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5522 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5524 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5525 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5526 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5527 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5528 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5529 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5530 check_added_monitors!(nodes[4], 0);
5531 expect_pending_htlcs_forwardable!(nodes[4]);
5532 check_added_monitors!(nodes[4], 1);
5534 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5535 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5536 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5537 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5538 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5539 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5541 // Fail 3rd below-dust and 7th above-dust HTLCs
5542 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5543 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5544 check_added_monitors!(nodes[5], 0);
5545 expect_pending_htlcs_forwardable!(nodes[5]);
5546 check_added_monitors!(nodes[5], 1);
5548 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5549 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5550 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5551 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5553 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5555 expect_pending_htlcs_forwardable!(nodes[3]);
5556 check_added_monitors!(nodes[3], 1);
5557 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5558 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5559 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5560 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5561 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5562 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5563 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5564 if deliver_last_raa {
5565 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5567 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5570 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5571 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5572 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5573 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5575 // We now broadcast the latest commitment transaction, which *should* result in failures for
5576 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5577 // the non-broadcast above-dust HTLCs.
5579 // Alternatively, we may broadcast the previous commitment transaction, which should only
5580 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5581 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5583 if announce_latest {
5584 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5586 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5588 let events = nodes[2].node.get_and_clear_pending_events();
5589 let close_event = if deliver_last_raa {
5590 assert_eq!(events.len(), 2);
5593 assert_eq!(events.len(), 1);
5597 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5598 _ => panic!("Unexpected event"),
5601 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5602 check_closed_broadcast!(nodes[2], true);
5603 if deliver_last_raa {
5604 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5606 expect_pending_htlcs_forwardable!(nodes[2]);
5608 check_added_monitors!(nodes[2], 3);
5610 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5611 assert_eq!(cs_msgs.len(), 2);
5612 let mut a_done = false;
5613 for msg in cs_msgs {
5615 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5616 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5617 // should be failed-backwards here.
5618 let target = if *node_id == nodes[0].node.get_our_node_id() {
5619 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5620 for htlc in &updates.update_fail_htlcs {
5621 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 });
5623 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5628 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5629 for htlc in &updates.update_fail_htlcs {
5630 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5632 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5633 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5636 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5637 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5638 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5639 if announce_latest {
5640 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5641 if *node_id == nodes[0].node.get_our_node_id() {
5642 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5645 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5647 _ => panic!("Unexpected event"),
5651 let as_events = nodes[0].node.get_and_clear_pending_events();
5652 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5653 let mut as_failds = HashSet::new();
5654 let mut as_updates = 0;
5655 for event in as_events.iter() {
5656 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5657 assert!(as_failds.insert(*payment_hash));
5658 if *payment_hash != payment_hash_2 {
5659 assert_eq!(*rejected_by_dest, deliver_last_raa);
5661 assert!(!rejected_by_dest);
5663 if network_update.is_some() {
5666 } else { panic!("Unexpected event"); }
5668 assert!(as_failds.contains(&payment_hash_1));
5669 assert!(as_failds.contains(&payment_hash_2));
5670 if announce_latest {
5671 assert!(as_failds.contains(&payment_hash_3));
5672 assert!(as_failds.contains(&payment_hash_5));
5674 assert!(as_failds.contains(&payment_hash_6));
5676 let bs_events = nodes[1].node.get_and_clear_pending_events();
5677 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5678 let mut bs_failds = HashSet::new();
5679 let mut bs_updates = 0;
5680 for event in bs_events.iter() {
5681 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5682 assert!(bs_failds.insert(*payment_hash));
5683 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5684 assert_eq!(*rejected_by_dest, deliver_last_raa);
5686 assert!(!rejected_by_dest);
5688 if network_update.is_some() {
5691 } else { panic!("Unexpected event"); }
5693 assert!(bs_failds.contains(&payment_hash_1));
5694 assert!(bs_failds.contains(&payment_hash_2));
5695 if announce_latest {
5696 assert!(bs_failds.contains(&payment_hash_4));
5698 assert!(bs_failds.contains(&payment_hash_5));
5700 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5701 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5702 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5703 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5704 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5705 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5709 fn test_fail_backwards_latest_remote_announce_a() {
5710 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5714 fn test_fail_backwards_latest_remote_announce_b() {
5715 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5719 fn test_fail_backwards_previous_remote_announce() {
5720 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5721 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5722 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5726 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5727 let chanmon_cfgs = create_chanmon_cfgs(2);
5728 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5729 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5730 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5732 // Create some initial channels
5733 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5735 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5736 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5737 assert_eq!(local_txn[0].input.len(), 1);
5738 check_spends!(local_txn[0], chan_1.3);
5740 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5741 mine_transaction(&nodes[0], &local_txn[0]);
5742 check_closed_broadcast!(nodes[0], true);
5743 check_added_monitors!(nodes[0], 1);
5744 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5745 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5747 let htlc_timeout = {
5748 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5749 assert_eq!(node_txn.len(), 2);
5750 check_spends!(node_txn[0], chan_1.3);
5751 assert_eq!(node_txn[1].input.len(), 1);
5752 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5753 check_spends!(node_txn[1], local_txn[0]);
5757 mine_transaction(&nodes[0], &htlc_timeout);
5758 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5759 expect_payment_failed!(nodes[0], our_payment_hash, true);
5761 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5762 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5763 assert_eq!(spend_txn.len(), 3);
5764 check_spends!(spend_txn[0], local_txn[0]);
5765 assert_eq!(spend_txn[1].input.len(), 1);
5766 check_spends!(spend_txn[1], htlc_timeout);
5767 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5768 assert_eq!(spend_txn[2].input.len(), 2);
5769 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5770 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5771 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5775 fn test_key_derivation_params() {
5776 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5777 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5778 // let us re-derive the channel key set to then derive a delayed_payment_key.
5780 let chanmon_cfgs = create_chanmon_cfgs(3);
5782 // We manually create the node configuration to backup the seed.
5783 let seed = [42; 32];
5784 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5785 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);
5786 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() };
5787 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5788 node_cfgs.remove(0);
5789 node_cfgs.insert(0, node);
5791 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5792 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5794 // Create some initial channels
5795 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5797 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5798 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5799 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5801 // Ensure all nodes are at the same height
5802 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5803 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5804 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5805 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5807 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5808 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5809 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5810 assert_eq!(local_txn_1[0].input.len(), 1);
5811 check_spends!(local_txn_1[0], chan_1.3);
5813 // We check funding pubkey are unique
5814 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]));
5815 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]));
5816 if from_0_funding_key_0 == from_1_funding_key_0
5817 || from_0_funding_key_0 == from_1_funding_key_1
5818 || from_0_funding_key_1 == from_1_funding_key_0
5819 || from_0_funding_key_1 == from_1_funding_key_1 {
5820 panic!("Funding pubkeys aren't unique");
5823 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5824 mine_transaction(&nodes[0], &local_txn_1[0]);
5825 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5826 check_closed_broadcast!(nodes[0], true);
5827 check_added_monitors!(nodes[0], 1);
5828 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5830 let htlc_timeout = {
5831 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5832 assert_eq!(node_txn[1].input.len(), 1);
5833 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5834 check_spends!(node_txn[1], local_txn_1[0]);
5838 mine_transaction(&nodes[0], &htlc_timeout);
5839 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5840 expect_payment_failed!(nodes[0], our_payment_hash, true);
5842 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5843 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5844 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5845 assert_eq!(spend_txn.len(), 3);
5846 check_spends!(spend_txn[0], local_txn_1[0]);
5847 assert_eq!(spend_txn[1].input.len(), 1);
5848 check_spends!(spend_txn[1], htlc_timeout);
5849 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5850 assert_eq!(spend_txn[2].input.len(), 2);
5851 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5852 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5853 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5857 fn test_static_output_closing_tx() {
5858 let chanmon_cfgs = create_chanmon_cfgs(2);
5859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5863 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5865 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5866 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5868 mine_transaction(&nodes[0], &closing_tx);
5869 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5870 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5872 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5873 assert_eq!(spend_txn.len(), 1);
5874 check_spends!(spend_txn[0], closing_tx);
5876 mine_transaction(&nodes[1], &closing_tx);
5877 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5878 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5880 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5881 assert_eq!(spend_txn.len(), 1);
5882 check_spends!(spend_txn[0], closing_tx);
5885 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5886 let chanmon_cfgs = create_chanmon_cfgs(2);
5887 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5888 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5889 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5890 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5892 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5894 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5895 // present in B's local commitment transaction, but none of A's commitment transactions.
5896 assert!(nodes[1].node.claim_funds(payment_preimage));
5897 check_added_monitors!(nodes[1], 1);
5899 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5900 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5901 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5903 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5904 check_added_monitors!(nodes[0], 1);
5905 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5906 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5907 check_added_monitors!(nodes[1], 1);
5909 let starting_block = nodes[1].best_block_info();
5910 let mut block = Block {
5911 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5914 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5915 connect_block(&nodes[1], &block);
5916 block.header.prev_blockhash = block.block_hash();
5918 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5919 check_closed_broadcast!(nodes[1], true);
5920 check_added_monitors!(nodes[1], 1);
5921 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5924 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5925 let chanmon_cfgs = create_chanmon_cfgs(2);
5926 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5927 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5928 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5929 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5931 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5932 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5933 check_added_monitors!(nodes[0], 1);
5935 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5937 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5938 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5939 // to "time out" the HTLC.
5941 let starting_block = nodes[1].best_block_info();
5942 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5944 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5945 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5946 header.prev_blockhash = header.block_hash();
5948 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5949 check_closed_broadcast!(nodes[0], true);
5950 check_added_monitors!(nodes[0], 1);
5951 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5954 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5955 let chanmon_cfgs = create_chanmon_cfgs(3);
5956 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5957 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5958 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5959 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5961 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5962 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5963 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5964 // actually revoked.
5965 let htlc_value = if use_dust { 50000 } else { 3000000 };
5966 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5967 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5968 expect_pending_htlcs_forwardable!(nodes[1]);
5969 check_added_monitors!(nodes[1], 1);
5971 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5972 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5973 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5974 check_added_monitors!(nodes[0], 1);
5975 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5976 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5977 check_added_monitors!(nodes[1], 1);
5978 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5979 check_added_monitors!(nodes[1], 1);
5980 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5982 if check_revoke_no_close {
5983 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5984 check_added_monitors!(nodes[0], 1);
5987 let starting_block = nodes[1].best_block_info();
5988 let mut block = Block {
5989 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5992 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5993 connect_block(&nodes[0], &block);
5994 block.header.prev_blockhash = block.block_hash();
5996 if !check_revoke_no_close {
5997 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5998 check_closed_broadcast!(nodes[0], true);
5999 check_added_monitors!(nodes[0], 1);
6000 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6002 let events = nodes[0].node.get_and_clear_pending_events();
6003 assert_eq!(events.len(), 2);
6004 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6005 assert_eq!(*payment_hash, our_payment_hash);
6006 } else { panic!("Unexpected event"); }
6007 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6008 assert_eq!(*payment_hash, our_payment_hash);
6009 } else { panic!("Unexpected event"); }
6013 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6014 // There are only a few cases to test here:
6015 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6016 // broadcastable commitment transactions result in channel closure,
6017 // * its included in an unrevoked-but-previous remote commitment transaction,
6018 // * its included in the latest remote or local commitment transactions.
6019 // We test each of the three possible commitment transactions individually and use both dust and
6021 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6022 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6023 // tested for at least one of the cases in other tests.
6025 fn htlc_claim_single_commitment_only_a() {
6026 do_htlc_claim_local_commitment_only(true);
6027 do_htlc_claim_local_commitment_only(false);
6029 do_htlc_claim_current_remote_commitment_only(true);
6030 do_htlc_claim_current_remote_commitment_only(false);
6034 fn htlc_claim_single_commitment_only_b() {
6035 do_htlc_claim_previous_remote_commitment_only(true, false);
6036 do_htlc_claim_previous_remote_commitment_only(false, false);
6037 do_htlc_claim_previous_remote_commitment_only(true, true);
6038 do_htlc_claim_previous_remote_commitment_only(false, true);
6043 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6044 let chanmon_cfgs = create_chanmon_cfgs(2);
6045 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6046 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6047 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6048 // Force duplicate randomness for every get-random call
6049 for node in nodes.iter() {
6050 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6053 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6054 let channel_value_satoshis=10000;
6055 let push_msat=10001;
6056 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6057 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6058 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6059 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6061 // Create a second channel with the same random values. This used to panic due to a colliding
6062 // channel_id, but now panics due to a colliding outbound SCID alias.
6063 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6067 fn bolt2_open_channel_sending_node_checks_part2() {
6068 let chanmon_cfgs = create_chanmon_cfgs(2);
6069 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6070 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6071 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6073 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6074 let channel_value_satoshis=2^24;
6075 let push_msat=10001;
6076 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6078 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6079 let channel_value_satoshis=10000;
6080 // Test when push_msat is equal to 1000 * funding_satoshis.
6081 let push_msat=1000*channel_value_satoshis+1;
6082 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6084 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6085 let channel_value_satoshis=10000;
6086 let push_msat=10001;
6087 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
6088 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6089 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6091 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6092 // 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
6093 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6095 // 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.
6096 assert!(BREAKDOWN_TIMEOUT>0);
6097 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6099 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6100 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6101 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6103 // 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.
6104 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6105 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6106 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6107 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6108 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6112 fn bolt2_open_channel_sane_dust_limit() {
6113 let chanmon_cfgs = create_chanmon_cfgs(2);
6114 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6115 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6116 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6118 let channel_value_satoshis=1000000;
6119 let push_msat=10001;
6120 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6121 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6122 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6123 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6125 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6126 let events = nodes[1].node.get_and_clear_pending_msg_events();
6127 let err_msg = match events[0] {
6128 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6131 _ => panic!("Unexpected event"),
6133 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6136 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6137 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6138 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6139 // is no longer affordable once it's freed.
6141 fn test_fail_holding_cell_htlc_upon_free() {
6142 let chanmon_cfgs = create_chanmon_cfgs(2);
6143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6145 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6146 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6148 // First nodes[0] generates an update_fee, setting the channel's
6149 // pending_update_fee.
6151 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6152 *feerate_lock += 20;
6154 nodes[0].node.timer_tick_occurred();
6155 check_added_monitors!(nodes[0], 1);
6157 let events = nodes[0].node.get_and_clear_pending_msg_events();
6158 assert_eq!(events.len(), 1);
6159 let (update_msg, commitment_signed) = match events[0] {
6160 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6161 (update_fee.as_ref(), commitment_signed)
6163 _ => panic!("Unexpected event"),
6166 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6168 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6169 let channel_reserve = chan_stat.channel_reserve_msat;
6170 let feerate = get_feerate!(nodes[0], chan.2);
6171 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6173 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6174 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6175 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6177 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6178 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6179 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6180 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6182 // Flush the pending fee update.
6183 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6184 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6185 check_added_monitors!(nodes[1], 1);
6186 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6187 check_added_monitors!(nodes[0], 1);
6189 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6190 // HTLC, but now that the fee has been raised the payment will now fail, causing
6191 // us to surface its failure to the user.
6192 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6193 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6194 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);
6195 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 {}",
6196 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6197 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6199 // Check that the payment failed to be sent out.
6200 let events = nodes[0].node.get_and_clear_pending_events();
6201 assert_eq!(events.len(), 1);
6203 &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, .. } => {
6204 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6205 assert_eq!(our_payment_hash.clone(), *payment_hash);
6206 assert_eq!(*rejected_by_dest, false);
6207 assert_eq!(*all_paths_failed, true);
6208 assert_eq!(*network_update, None);
6209 assert_eq!(*short_channel_id, None);
6210 assert_eq!(*error_code, None);
6211 assert_eq!(*error_data, None);
6213 _ => panic!("Unexpected event"),
6217 // Test that if multiple HTLCs are released from the holding cell and one is
6218 // valid but the other is no longer valid upon release, the valid HTLC can be
6219 // successfully completed while the other one fails as expected.
6221 fn test_free_and_fail_holding_cell_htlcs() {
6222 let chanmon_cfgs = create_chanmon_cfgs(2);
6223 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6224 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6225 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6226 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6228 // First nodes[0] generates an update_fee, setting the channel's
6229 // pending_update_fee.
6231 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6232 *feerate_lock += 200;
6234 nodes[0].node.timer_tick_occurred();
6235 check_added_monitors!(nodes[0], 1);
6237 let events = nodes[0].node.get_and_clear_pending_msg_events();
6238 assert_eq!(events.len(), 1);
6239 let (update_msg, commitment_signed) = match events[0] {
6240 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6241 (update_fee.as_ref(), commitment_signed)
6243 _ => panic!("Unexpected event"),
6246 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6248 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6249 let channel_reserve = chan_stat.channel_reserve_msat;
6250 let feerate = get_feerate!(nodes[0], chan.2);
6251 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6253 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6255 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6256 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6257 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6259 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6260 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6261 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6262 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6263 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6264 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6265 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6267 // Flush the pending fee update.
6268 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6269 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6270 check_added_monitors!(nodes[1], 1);
6271 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6272 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6273 check_added_monitors!(nodes[0], 2);
6275 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6276 // but now that the fee has been raised the second payment will now fail, causing us
6277 // to surface its failure to the user. The first payment should succeed.
6278 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6279 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6280 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);
6281 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 {}",
6282 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6283 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6285 // Check that the second payment failed to be sent out.
6286 let events = nodes[0].node.get_and_clear_pending_events();
6287 assert_eq!(events.len(), 1);
6289 &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, .. } => {
6290 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6291 assert_eq!(payment_hash_2.clone(), *payment_hash);
6292 assert_eq!(*rejected_by_dest, false);
6293 assert_eq!(*all_paths_failed, true);
6294 assert_eq!(*network_update, None);
6295 assert_eq!(*short_channel_id, None);
6296 assert_eq!(*error_code, None);
6297 assert_eq!(*error_data, None);
6299 _ => panic!("Unexpected event"),
6302 // Complete the first payment and the RAA from the fee update.
6303 let (payment_event, send_raa_event) = {
6304 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6305 assert_eq!(msgs.len(), 2);
6306 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6308 let raa = match send_raa_event {
6309 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6310 _ => panic!("Unexpected event"),
6312 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6313 check_added_monitors!(nodes[1], 1);
6314 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6315 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6316 let events = nodes[1].node.get_and_clear_pending_events();
6317 assert_eq!(events.len(), 1);
6319 Event::PendingHTLCsForwardable { .. } => {},
6320 _ => panic!("Unexpected event"),
6322 nodes[1].node.process_pending_htlc_forwards();
6323 let events = nodes[1].node.get_and_clear_pending_events();
6324 assert_eq!(events.len(), 1);
6326 Event::PaymentReceived { .. } => {},
6327 _ => panic!("Unexpected event"),
6329 nodes[1].node.claim_funds(payment_preimage_1);
6330 check_added_monitors!(nodes[1], 1);
6331 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6332 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6333 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6334 expect_payment_sent!(nodes[0], payment_preimage_1);
6337 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6338 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6339 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6342 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6343 let chanmon_cfgs = create_chanmon_cfgs(3);
6344 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6345 // When this test was written, the default base fee floated based on the HTLC count.
6346 // It is now fixed, so we simply set the fee to the expected value here.
6347 let mut config = test_default_channel_config();
6348 config.channel_options.forwarding_fee_base_msat = 196;
6349 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6350 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6351 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6352 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6354 // First nodes[1] generates an update_fee, setting the channel's
6355 // pending_update_fee.
6357 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6358 *feerate_lock += 20;
6360 nodes[1].node.timer_tick_occurred();
6361 check_added_monitors!(nodes[1], 1);
6363 let events = nodes[1].node.get_and_clear_pending_msg_events();
6364 assert_eq!(events.len(), 1);
6365 let (update_msg, commitment_signed) = match events[0] {
6366 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6367 (update_fee.as_ref(), commitment_signed)
6369 _ => panic!("Unexpected event"),
6372 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6374 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6375 let channel_reserve = chan_stat.channel_reserve_msat;
6376 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6377 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6379 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6381 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6382 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6383 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6384 let payment_event = {
6385 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6386 check_added_monitors!(nodes[0], 1);
6388 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6389 assert_eq!(events.len(), 1);
6391 SendEvent::from_event(events.remove(0))
6393 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6394 check_added_monitors!(nodes[1], 0);
6395 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6396 expect_pending_htlcs_forwardable!(nodes[1]);
6398 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6399 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6401 // Flush the pending fee update.
6402 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6403 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6404 check_added_monitors!(nodes[2], 1);
6405 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6406 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6407 check_added_monitors!(nodes[1], 2);
6409 // A final RAA message is generated to finalize the fee update.
6410 let events = nodes[1].node.get_and_clear_pending_msg_events();
6411 assert_eq!(events.len(), 1);
6413 let raa_msg = match &events[0] {
6414 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6417 _ => panic!("Unexpected event"),
6420 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6421 check_added_monitors!(nodes[2], 1);
6422 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6424 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6425 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6426 assert_eq!(process_htlc_forwards_event.len(), 1);
6427 match &process_htlc_forwards_event[0] {
6428 &Event::PendingHTLCsForwardable { .. } => {},
6429 _ => panic!("Unexpected event"),
6432 // In response, we call ChannelManager's process_pending_htlc_forwards
6433 nodes[1].node.process_pending_htlc_forwards();
6434 check_added_monitors!(nodes[1], 1);
6436 // This causes the HTLC to be failed backwards.
6437 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6438 assert_eq!(fail_event.len(), 1);
6439 let (fail_msg, commitment_signed) = match &fail_event[0] {
6440 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6441 assert_eq!(updates.update_add_htlcs.len(), 0);
6442 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6443 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6444 assert_eq!(updates.update_fail_htlcs.len(), 1);
6445 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6447 _ => panic!("Unexpected event"),
6450 // Pass the failure messages back to nodes[0].
6451 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6452 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6454 // Complete the HTLC failure+removal process.
6455 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6456 check_added_monitors!(nodes[0], 1);
6457 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6458 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6459 check_added_monitors!(nodes[1], 2);
6460 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6461 assert_eq!(final_raa_event.len(), 1);
6462 let raa = match &final_raa_event[0] {
6463 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6464 _ => panic!("Unexpected event"),
6466 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6467 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6468 check_added_monitors!(nodes[0], 1);
6471 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6472 // 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.
6473 //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.
6476 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6477 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6478 let chanmon_cfgs = create_chanmon_cfgs(2);
6479 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6480 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6481 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6482 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6484 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6485 route.paths[0][0].fee_msat = 100;
6487 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6488 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6489 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6490 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6494 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6495 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6496 let chanmon_cfgs = create_chanmon_cfgs(2);
6497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6499 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6500 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6502 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6503 route.paths[0][0].fee_msat = 0;
6504 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6505 assert_eq!(err, "Cannot send 0-msat HTLC"));
6507 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6508 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6512 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6513 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6514 let chanmon_cfgs = create_chanmon_cfgs(2);
6515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6517 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6518 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6520 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6521 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6522 check_added_monitors!(nodes[0], 1);
6523 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6524 updates.update_add_htlcs[0].amount_msat = 0;
6526 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6527 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6528 check_closed_broadcast!(nodes[1], true).unwrap();
6529 check_added_monitors!(nodes[1], 1);
6530 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6534 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6535 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6536 //It is enforced when constructing a route.
6537 let chanmon_cfgs = create_chanmon_cfgs(2);
6538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6540 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6541 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6543 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6544 .with_features(InvoiceFeatures::known());
6545 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6546 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6547 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6548 assert_eq!(err, &"Channel CLTV overflowed?"));
6552 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6553 //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.
6554 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6555 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6556 let chanmon_cfgs = create_chanmon_cfgs(2);
6557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6559 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6560 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6561 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6563 for i in 0..max_accepted_htlcs {
6564 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6565 let payment_event = {
6566 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6567 check_added_monitors!(nodes[0], 1);
6569 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6570 assert_eq!(events.len(), 1);
6571 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6572 assert_eq!(htlcs[0].htlc_id, i);
6576 SendEvent::from_event(events.remove(0))
6578 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6579 check_added_monitors!(nodes[1], 0);
6580 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6582 expect_pending_htlcs_forwardable!(nodes[1]);
6583 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6585 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6586 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6587 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6589 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6590 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6594 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6595 //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.
6596 let chanmon_cfgs = create_chanmon_cfgs(2);
6597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6599 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6600 let channel_value = 100000;
6601 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6602 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6604 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6606 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6607 // Manually create a route over our max in flight (which our router normally automatically
6609 route.paths[0][0].fee_msat = max_in_flight + 1;
6610 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6611 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)));
6613 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6614 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);
6616 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6619 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6621 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6622 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6623 let chanmon_cfgs = create_chanmon_cfgs(2);
6624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6626 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6627 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6628 let htlc_minimum_msat: u64;
6630 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6631 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6632 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6635 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6636 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6637 check_added_monitors!(nodes[0], 1);
6638 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6639 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6640 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6641 assert!(nodes[1].node.list_channels().is_empty());
6642 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6643 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()));
6644 check_added_monitors!(nodes[1], 1);
6645 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6649 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6650 //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
6651 let chanmon_cfgs = create_chanmon_cfgs(2);
6652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6654 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6655 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6657 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6658 let channel_reserve = chan_stat.channel_reserve_msat;
6659 let feerate = get_feerate!(nodes[0], chan.2);
6660 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6661 // The 2* and +1 are for the fee spike reserve.
6662 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6664 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6665 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6666 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6667 check_added_monitors!(nodes[0], 1);
6668 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6670 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6671 // at this time channel-initiatee receivers are not required to enforce that senders
6672 // respect the fee_spike_reserve.
6673 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6674 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6676 assert!(nodes[1].node.list_channels().is_empty());
6677 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6678 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6679 check_added_monitors!(nodes[1], 1);
6680 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6684 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6685 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6686 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6687 let chanmon_cfgs = create_chanmon_cfgs(2);
6688 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6689 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6690 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6691 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6693 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6694 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6695 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6696 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6697 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6698 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6700 let mut msg = msgs::UpdateAddHTLC {
6704 payment_hash: our_payment_hash,
6705 cltv_expiry: htlc_cltv,
6706 onion_routing_packet: onion_packet.clone(),
6709 for i in 0..super::channel::OUR_MAX_HTLCS {
6710 msg.htlc_id = i as u64;
6711 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6713 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6714 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6716 assert!(nodes[1].node.list_channels().is_empty());
6717 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6718 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6719 check_added_monitors!(nodes[1], 1);
6720 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6724 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6725 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6726 let chanmon_cfgs = create_chanmon_cfgs(2);
6727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6729 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6730 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6732 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6733 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6734 check_added_monitors!(nodes[0], 1);
6735 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6736 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6737 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6739 assert!(nodes[1].node.list_channels().is_empty());
6740 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6741 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6742 check_added_monitors!(nodes[1], 1);
6743 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6747 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6748 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6749 let chanmon_cfgs = create_chanmon_cfgs(2);
6750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6752 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6754 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6755 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6756 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6757 check_added_monitors!(nodes[0], 1);
6758 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6759 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6760 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6762 assert!(nodes[1].node.list_channels().is_empty());
6763 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6764 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6765 check_added_monitors!(nodes[1], 1);
6766 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6770 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6771 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6772 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6773 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6774 let chanmon_cfgs = create_chanmon_cfgs(2);
6775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6777 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6779 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6780 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6781 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6782 check_added_monitors!(nodes[0], 1);
6783 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6786 //Disconnect and Reconnect
6787 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6788 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6789 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6790 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6791 assert_eq!(reestablish_1.len(), 1);
6792 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6793 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6794 assert_eq!(reestablish_2.len(), 1);
6795 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6796 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6797 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6798 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6801 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6802 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6803 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6804 check_added_monitors!(nodes[1], 1);
6805 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6807 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6809 assert!(nodes[1].node.list_channels().is_empty());
6810 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6811 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6812 check_added_monitors!(nodes[1], 1);
6813 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6817 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6818 //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.
6820 let chanmon_cfgs = create_chanmon_cfgs(2);
6821 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6822 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6823 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6824 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6825 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6826 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6828 check_added_monitors!(nodes[0], 1);
6829 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6830 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6832 let update_msg = msgs::UpdateFulfillHTLC{
6835 payment_preimage: our_payment_preimage,
6838 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6840 assert!(nodes[0].node.list_channels().is_empty());
6841 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6842 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()));
6843 check_added_monitors!(nodes[0], 1);
6844 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6848 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6849 //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.
6851 let chanmon_cfgs = create_chanmon_cfgs(2);
6852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6854 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6855 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6857 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6858 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6859 check_added_monitors!(nodes[0], 1);
6860 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6861 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6863 let update_msg = msgs::UpdateFailHTLC{
6866 reason: msgs::OnionErrorPacket { data: Vec::new()},
6869 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6871 assert!(nodes[0].node.list_channels().is_empty());
6872 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6873 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()));
6874 check_added_monitors!(nodes[0], 1);
6875 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6879 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6880 //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.
6882 let chanmon_cfgs = create_chanmon_cfgs(2);
6883 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6884 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6885 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6886 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6888 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6889 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6890 check_added_monitors!(nodes[0], 1);
6891 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6892 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6893 let update_msg = msgs::UpdateFailMalformedHTLC{
6896 sha256_of_onion: [1; 32],
6897 failure_code: 0x8000,
6900 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6902 assert!(nodes[0].node.list_channels().is_empty());
6903 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6904 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()));
6905 check_added_monitors!(nodes[0], 1);
6906 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6910 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6911 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6913 let chanmon_cfgs = create_chanmon_cfgs(2);
6914 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6915 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6916 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6917 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6919 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6921 nodes[1].node.claim_funds(our_payment_preimage);
6922 check_added_monitors!(nodes[1], 1);
6924 let events = nodes[1].node.get_and_clear_pending_msg_events();
6925 assert_eq!(events.len(), 1);
6926 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6928 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, .. } } => {
6929 assert!(update_add_htlcs.is_empty());
6930 assert_eq!(update_fulfill_htlcs.len(), 1);
6931 assert!(update_fail_htlcs.is_empty());
6932 assert!(update_fail_malformed_htlcs.is_empty());
6933 assert!(update_fee.is_none());
6934 update_fulfill_htlcs[0].clone()
6936 _ => panic!("Unexpected event"),
6940 update_fulfill_msg.htlc_id = 1;
6942 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6944 assert!(nodes[0].node.list_channels().is_empty());
6945 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6946 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6947 check_added_monitors!(nodes[0], 1);
6948 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6952 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6953 //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.
6955 let chanmon_cfgs = create_chanmon_cfgs(2);
6956 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6958 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6959 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6961 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6963 nodes[1].node.claim_funds(our_payment_preimage);
6964 check_added_monitors!(nodes[1], 1);
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 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
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 mine_transaction(&nodes[1], &remote_txn[0]);
7963 check_added_monitors!(nodes[1], 2);
7964 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7966 // One or more claim tx should have been broadcast, check it
7970 let feerate_timeout;
7971 let feerate_preimage;
7973 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7974 // 9 transactions including:
7975 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7976 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7977 // 2 * HTLC-Success (one RBF bump we'll check later)
7979 assert_eq!(node_txn.len(), 8);
7980 assert_eq!(node_txn[0].input.len(), 1);
7981 assert_eq!(node_txn[6].input.len(), 1);
7982 check_spends!(node_txn[0], remote_txn[0]);
7983 check_spends!(node_txn[6], remote_txn[0]);
7985 check_spends!(node_txn[1], chan.3);
7986 check_spends!(node_txn[2], node_txn[1]);
7988 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
7989 preimage_bump = node_txn[3].clone();
7990 check_spends!(node_txn[3], remote_txn[0]);
7992 assert_eq!(node_txn[1], node_txn[4]);
7993 assert_eq!(node_txn[2], node_txn[5]);
7995 preimage_bump = node_txn[7].clone();
7996 check_spends!(node_txn[7], remote_txn[0]);
7997 assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
7999 assert_eq!(node_txn[1], node_txn[3]);
8000 assert_eq!(node_txn[2], node_txn[4]);
8003 timeout = node_txn[6].txid();
8004 let index = node_txn[6].input[0].previous_output.vout;
8005 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8006 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8008 preimage = node_txn[0].txid();
8009 let index = node_txn[0].input[0].previous_output.vout;
8010 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8011 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8015 assert_ne!(feerate_timeout, 0);
8016 assert_ne!(feerate_preimage, 0);
8018 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8019 connect_blocks(&nodes[1], 15);
8021 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8022 assert_eq!(node_txn.len(), 1);
8023 assert_eq!(node_txn[0].input.len(), 1);
8024 assert_eq!(preimage_bump.input.len(), 1);
8025 check_spends!(node_txn[0], remote_txn[0]);
8026 check_spends!(preimage_bump, remote_txn[0]);
8028 let index = preimage_bump.input[0].previous_output.vout;
8029 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8030 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8031 assert!(new_feerate * 100 > feerate_timeout * 125);
8032 assert_ne!(timeout, preimage_bump.txid());
8034 let index = node_txn[0].input[0].previous_output.vout;
8035 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8036 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8037 assert!(new_feerate * 100 > feerate_preimage * 125);
8038 assert_ne!(preimage, node_txn[0].txid());
8043 nodes[1].node.get_and_clear_pending_events();
8044 nodes[1].node.get_and_clear_pending_msg_events();
8048 fn test_counterparty_raa_skip_no_crash() {
8049 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8050 // commitment transaction, we would have happily carried on and provided them the next
8051 // commitment transaction based on one RAA forward. This would probably eventually have led to
8052 // channel closure, but it would not have resulted in funds loss. Still, our
8053 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8054 // check simply that the channel is closed in response to such an RAA, but don't check whether
8055 // we decide to punish our counterparty for revoking their funds (as we don't currently
8057 let chanmon_cfgs = create_chanmon_cfgs(2);
8058 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8059 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8060 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8061 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8063 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8064 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8066 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8068 // Make signer believe we got a counterparty signature, so that it allows the revocation
8069 keys.get_enforcement_state().last_holder_commitment -= 1;
8070 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8072 // Must revoke without gaps
8073 keys.get_enforcement_state().last_holder_commitment -= 1;
8074 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8076 keys.get_enforcement_state().last_holder_commitment -= 1;
8077 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8078 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8080 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8081 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8082 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8083 check_added_monitors!(nodes[1], 1);
8084 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8088 fn test_bump_txn_sanitize_tracking_maps() {
8089 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8090 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8092 let chanmon_cfgs = create_chanmon_cfgs(2);
8093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8097 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8098 // Lock HTLC in both directions
8099 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8100 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8102 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8103 assert_eq!(revoked_local_txn[0].input.len(), 1);
8104 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8106 // Revoke local commitment tx
8107 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8109 // Broadcast set of revoked txn on A
8110 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8111 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8112 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8114 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8115 check_closed_broadcast!(nodes[0], true);
8116 check_added_monitors!(nodes[0], 1);
8117 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8119 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8120 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8121 check_spends!(node_txn[0], revoked_local_txn[0]);
8122 check_spends!(node_txn[1], revoked_local_txn[0]);
8123 check_spends!(node_txn[2], revoked_local_txn[0]);
8124 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8128 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8129 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8130 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8132 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8133 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8134 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8139 fn test_pending_claimed_htlc_no_balance_underflow() {
8140 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8141 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8142 let chanmon_cfgs = create_chanmon_cfgs(2);
8143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8145 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8146 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8148 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8149 nodes[1].node.claim_funds(payment_preimage);
8150 check_added_monitors!(nodes[1], 1);
8151 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8153 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8154 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8155 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8156 check_added_monitors!(nodes[0], 1);
8157 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8159 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8160 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8161 // can get our balance.
8163 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8164 // the public key of the only hop. This works around ChannelDetails not showing the
8165 // almost-claimed HTLC as available balance.
8166 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8167 route.payment_params = None; // This is all wrong, but unnecessary
8168 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8169 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8170 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8172 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8176 fn test_channel_conf_timeout() {
8177 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8178 // confirm within 2016 blocks, as recommended by BOLT 2.
8179 let chanmon_cfgs = create_chanmon_cfgs(2);
8180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8182 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8184 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8186 // The outbound node should wait forever for confirmation:
8187 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8188 // copied here instead of directly referencing the constant.
8189 connect_blocks(&nodes[0], 2016);
8190 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8192 // The inbound node should fail the channel after exactly 2016 blocks
8193 connect_blocks(&nodes[1], 2015);
8194 check_added_monitors!(nodes[1], 0);
8195 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8197 connect_blocks(&nodes[1], 1);
8198 check_added_monitors!(nodes[1], 1);
8199 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8200 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8201 assert_eq!(close_ev.len(), 1);
8203 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8204 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8205 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8207 _ => panic!("Unexpected event"),
8212 fn test_override_channel_config() {
8213 let chanmon_cfgs = create_chanmon_cfgs(2);
8214 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8215 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8216 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8218 // Node0 initiates a channel to node1 using the override config.
8219 let mut override_config = UserConfig::default();
8220 override_config.own_channel_config.our_to_self_delay = 200;
8222 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8224 // Assert the channel created by node0 is using the override config.
8225 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8226 assert_eq!(res.channel_flags, 0);
8227 assert_eq!(res.to_self_delay, 200);
8231 fn test_override_0msat_htlc_minimum() {
8232 let mut zero_config = UserConfig::default();
8233 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8234 let chanmon_cfgs = create_chanmon_cfgs(2);
8235 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8236 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8237 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8239 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8240 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8241 assert_eq!(res.htlc_minimum_msat, 1);
8243 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8244 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8245 assert_eq!(res.htlc_minimum_msat, 1);
8249 fn test_channel_update_has_correct_htlc_maximum_msat() {
8250 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8251 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8252 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8253 // 90% of the `channel_value`.
8254 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8256 let mut config_30_percent = UserConfig::default();
8257 config_30_percent.channel_options.announced_channel = true;
8258 config_30_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8259 let mut config_50_percent = UserConfig::default();
8260 config_50_percent.channel_options.announced_channel = true;
8261 config_50_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8262 let mut config_95_percent = UserConfig::default();
8263 config_95_percent.channel_options.announced_channel = true;
8264 config_95_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8265 let mut config_100_percent = UserConfig::default();
8266 config_100_percent.channel_options.announced_channel = true;
8267 config_100_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8269 let chanmon_cfgs = create_chanmon_cfgs(4);
8270 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8271 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)]);
8272 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8274 let channel_value_satoshis = 100000;
8275 let channel_value_msat = channel_value_satoshis * 1000;
8276 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8277 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8278 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8280 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());
8281 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());
8283 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8284 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8285 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8286 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8287 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8288 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8290 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8291 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8293 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8294 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8295 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8297 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8301 fn test_manually_accept_inbound_channel_request() {
8302 let mut manually_accept_conf = UserConfig::default();
8303 manually_accept_conf.manually_accept_inbound_channels = true;
8304 let chanmon_cfgs = create_chanmon_cfgs(2);
8305 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8306 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8307 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8309 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8310 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8312 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8314 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8315 // accepting the inbound channel request.
8316 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8318 let events = nodes[1].node.get_and_clear_pending_events();
8320 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8321 nodes[1].node.accept_inbound_channel(&temporary_channel_id, 23).unwrap();
8323 _ => panic!("Unexpected event"),
8326 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8327 assert_eq!(accept_msg_ev.len(), 1);
8329 match accept_msg_ev[0] {
8330 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8331 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8333 _ => panic!("Unexpected event"),
8336 nodes[1].node.force_close_channel(&temp_channel_id).unwrap();
8338 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8339 assert_eq!(close_msg_ev.len(), 1);
8341 let events = nodes[1].node.get_and_clear_pending_events();
8343 Event::ChannelClosed { user_channel_id, .. } => {
8344 assert_eq!(user_channel_id, 23);
8346 _ => panic!("Unexpected event"),
8351 fn test_manually_reject_inbound_channel_request() {
8352 let mut manually_accept_conf = UserConfig::default();
8353 manually_accept_conf.manually_accept_inbound_channels = true;
8354 let chanmon_cfgs = create_chanmon_cfgs(2);
8355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8357 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8359 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8360 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8362 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8364 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8365 // rejecting the inbound channel request.
8366 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8368 let events = nodes[1].node.get_and_clear_pending_events();
8370 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8371 nodes[1].node.force_close_channel(&temporary_channel_id).unwrap();
8373 _ => panic!("Unexpected event"),
8376 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8377 assert_eq!(close_msg_ev.len(), 1);
8379 match close_msg_ev[0] {
8380 MessageSendEvent::HandleError { ref node_id, .. } => {
8381 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8383 _ => panic!("Unexpected event"),
8385 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8389 fn test_reject_funding_before_inbound_channel_accepted() {
8390 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8391 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8392 // the node operator before the counterparty sends a `FundingCreated` message. If a
8393 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8394 // and the channel should be closed.
8395 let mut manually_accept_conf = UserConfig::default();
8396 manually_accept_conf.manually_accept_inbound_channels = true;
8397 let chanmon_cfgs = create_chanmon_cfgs(2);
8398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8400 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8402 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8403 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8404 let temp_channel_id = res.temporary_channel_id;
8406 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8408 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8409 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8411 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8412 nodes[1].node.get_and_clear_pending_events();
8414 // Get the `AcceptChannel` message of `nodes[1]` without calling
8415 // `ChannelManager::accept_inbound_channel`, which generates a
8416 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8417 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8418 // succeed when `nodes[0]` is passed to it.
8421 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8422 let accept_chan_msg = channel.get_accept_channel_message();
8423 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8426 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8428 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8429 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8431 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8432 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8434 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8435 assert_eq!(close_msg_ev.len(), 1);
8437 let expected_err = "FundingCreated message received before the channel was accepted";
8438 match close_msg_ev[0] {
8439 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8440 assert_eq!(msg.channel_id, temp_channel_id);
8441 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8442 assert_eq!(msg.data, expected_err);
8444 _ => panic!("Unexpected event"),
8447 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8451 fn test_can_not_accept_inbound_channel_twice() {
8452 let mut manually_accept_conf = UserConfig::default();
8453 manually_accept_conf.manually_accept_inbound_channels = true;
8454 let chanmon_cfgs = create_chanmon_cfgs(2);
8455 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8456 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8457 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8459 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8460 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8462 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8464 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8465 // accepting the inbound channel request.
8466 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8468 let events = nodes[1].node.get_and_clear_pending_events();
8470 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8471 nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0).unwrap();
8472 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0);
8474 Err(APIError::APIMisuseError { err }) => {
8475 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8477 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8478 Err(_) => panic!("Unexpected Error"),
8481 _ => panic!("Unexpected event"),
8484 // Ensure that the channel wasn't closed after attempting to accept it twice.
8485 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8486 assert_eq!(accept_msg_ev.len(), 1);
8488 match accept_msg_ev[0] {
8489 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8490 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8492 _ => panic!("Unexpected event"),
8497 fn test_can_not_accept_unknown_inbound_channel() {
8498 let chanmon_cfg = create_chanmon_cfgs(1);
8499 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
8500 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
8501 let node = create_network(1, &node_cfg, &node_chanmgr)[0].node;
8503 let unknown_channel_id = [0; 32];
8504 let api_res = node.accept_inbound_channel(&unknown_channel_id, 0);
8506 Err(APIError::ChannelUnavailable { err }) => {
8507 assert_eq!(err, "Can't accept a channel that doesn't exist");
8509 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8510 Err(_) => panic!("Unexpected Error"),
8515 fn test_simple_mpp() {
8516 // Simple test of sending a multi-path payment.
8517 let chanmon_cfgs = create_chanmon_cfgs(4);
8518 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8519 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8520 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8522 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8523 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8524 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8525 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8527 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8528 let path = route.paths[0].clone();
8529 route.paths.push(path);
8530 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8531 route.paths[0][0].short_channel_id = chan_1_id;
8532 route.paths[0][1].short_channel_id = chan_3_id;
8533 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8534 route.paths[1][0].short_channel_id = chan_2_id;
8535 route.paths[1][1].short_channel_id = chan_4_id;
8536 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8537 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8541 fn test_preimage_storage() {
8542 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8543 let chanmon_cfgs = create_chanmon_cfgs(2);
8544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8546 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8548 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8551 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8552 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8553 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8554 check_added_monitors!(nodes[0], 1);
8555 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8556 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8557 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8558 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8560 // Note that after leaving the above scope we have no knowledge of any arguments or return
8561 // values from previous calls.
8562 expect_pending_htlcs_forwardable!(nodes[1]);
8563 let events = nodes[1].node.get_and_clear_pending_events();
8564 assert_eq!(events.len(), 1);
8566 Event::PaymentReceived { ref purpose, .. } => {
8568 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8569 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8571 _ => panic!("expected PaymentPurpose::InvoicePayment")
8574 _ => panic!("Unexpected event"),
8579 #[allow(deprecated)]
8580 fn test_secret_timeout() {
8581 // Simple test of payment secret storage time outs. After
8582 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8583 let chanmon_cfgs = create_chanmon_cfgs(2);
8584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8588 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8590 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8592 // We should fail to register the same payment hash twice, at least until we've connected a
8593 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8594 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8595 assert_eq!(err, "Duplicate payment hash");
8596 } else { panic!(); }
8598 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8600 header: BlockHeader {
8602 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8603 merkle_root: Default::default(),
8604 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8608 connect_block(&nodes[1], &block);
8609 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8610 assert_eq!(err, "Duplicate payment hash");
8611 } else { panic!(); }
8613 // If we then connect the second block, we should be able to register the same payment hash
8614 // again (this time getting a new payment secret).
8615 block.header.prev_blockhash = block.header.block_hash();
8616 block.header.time += 1;
8617 connect_block(&nodes[1], &block);
8618 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8619 assert_ne!(payment_secret_1, our_payment_secret);
8622 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8623 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8624 check_added_monitors!(nodes[0], 1);
8625 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8626 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8627 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8628 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8630 // Note that after leaving the above scope we have no knowledge of any arguments or return
8631 // values from previous calls.
8632 expect_pending_htlcs_forwardable!(nodes[1]);
8633 let events = nodes[1].node.get_and_clear_pending_events();
8634 assert_eq!(events.len(), 1);
8636 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8637 assert!(payment_preimage.is_none());
8638 assert_eq!(payment_secret, our_payment_secret);
8639 // We don't actually have the payment preimage with which to claim this payment!
8641 _ => panic!("Unexpected event"),
8646 fn test_bad_secret_hash() {
8647 // Simple test of unregistered payment hash/invalid payment secret handling
8648 let chanmon_cfgs = create_chanmon_cfgs(2);
8649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8651 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8653 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8655 let random_payment_hash = PaymentHash([42; 32]);
8656 let random_payment_secret = PaymentSecret([43; 32]);
8657 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8658 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8660 // All the below cases should end up being handled exactly identically, so we macro the
8661 // resulting events.
8662 macro_rules! handle_unknown_invalid_payment_data {
8664 check_added_monitors!(nodes[0], 1);
8665 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8666 let payment_event = SendEvent::from_event(events.pop().unwrap());
8667 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8668 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8670 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8671 // again to process the pending backwards-failure of the HTLC
8672 expect_pending_htlcs_forwardable!(nodes[1]);
8673 expect_pending_htlcs_forwardable!(nodes[1]);
8674 check_added_monitors!(nodes[1], 1);
8676 // We should fail the payment back
8677 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8678 match events.pop().unwrap() {
8679 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8680 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8681 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8683 _ => panic!("Unexpected event"),
8688 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8689 // Error data is the HTLC value (100,000) and current block height
8690 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8692 // Send a payment with the right payment hash but the wrong payment secret
8693 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8694 handle_unknown_invalid_payment_data!();
8695 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8697 // Send a payment with a random payment hash, but the right payment secret
8698 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8699 handle_unknown_invalid_payment_data!();
8700 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8702 // Send a payment with a random payment hash and random payment secret
8703 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8704 handle_unknown_invalid_payment_data!();
8705 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8709 fn test_update_err_monitor_lockdown() {
8710 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8711 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8712 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8714 // This scenario may happen in a watchtower setup, where watchtower process a block height
8715 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8716 // commitment at same time.
8718 let chanmon_cfgs = create_chanmon_cfgs(2);
8719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8721 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8723 // Create some initial channel
8724 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8725 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8727 // Rebalance the network to generate htlc in the two directions
8728 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8730 // Route a HTLC from node 0 to node 1 (but don't settle)
8731 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8733 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8734 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8735 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8736 let persister = test_utils::TestPersister::new();
8738 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8739 let mut w = test_utils::TestVecWriter(Vec::new());
8740 monitor.write(&mut w).unwrap();
8741 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8742 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8743 assert!(new_monitor == *monitor);
8744 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);
8745 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8748 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8749 let block = Block { header, txdata: vec![] };
8750 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8751 // transaction lock time requirements here.
8752 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8753 watchtower.chain_monitor.block_connected(&block, 200);
8755 // Try to update ChannelMonitor
8756 assert!(nodes[1].node.claim_funds(preimage));
8757 check_added_monitors!(nodes[1], 1);
8758 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8759 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8760 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8761 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8762 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8763 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8764 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8765 } else { assert!(false); }
8766 } else { assert!(false); };
8767 // Our local monitor is in-sync and hasn't processed yet timeout
8768 check_added_monitors!(nodes[0], 1);
8769 let events = nodes[0].node.get_and_clear_pending_events();
8770 assert_eq!(events.len(), 1);
8774 fn test_concurrent_monitor_claim() {
8775 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8776 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8777 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8778 // state N+1 confirms. Alice claims output from state N+1.
8780 let chanmon_cfgs = create_chanmon_cfgs(2);
8781 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8782 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8783 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8785 // Create some initial channel
8786 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8787 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8789 // Rebalance the network to generate htlc in the two directions
8790 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8792 // Route a HTLC from node 0 to node 1 (but don't settle)
8793 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8795 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8796 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8797 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8798 let persister = test_utils::TestPersister::new();
8799 let watchtower_alice = {
8800 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8801 let mut w = test_utils::TestVecWriter(Vec::new());
8802 monitor.write(&mut w).unwrap();
8803 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8804 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8805 assert!(new_monitor == *monitor);
8806 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);
8807 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8810 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8811 let block = Block { header, txdata: vec![] };
8812 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8813 // transaction lock time requirements here.
8814 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8815 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8817 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8819 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8820 assert_eq!(txn.len(), 2);
8824 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8825 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8826 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8827 let persister = test_utils::TestPersister::new();
8828 let watchtower_bob = {
8829 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8830 let mut w = test_utils::TestVecWriter(Vec::new());
8831 monitor.write(&mut w).unwrap();
8832 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8833 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8834 assert!(new_monitor == *monitor);
8835 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8836 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8839 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8840 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8842 // Route another payment to generate another update with still previous HTLC pending
8843 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8845 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8847 check_added_monitors!(nodes[1], 1);
8849 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8850 assert_eq!(updates.update_add_htlcs.len(), 1);
8851 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8852 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8853 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8854 // Watchtower Alice should already have seen the block and reject the update
8855 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8856 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8857 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8858 } else { assert!(false); }
8859 } else { assert!(false); };
8860 // Our local monitor is in-sync and hasn't processed yet timeout
8861 check_added_monitors!(nodes[0], 1);
8863 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8864 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8865 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8867 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8870 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8871 assert_eq!(txn.len(), 2);
8872 bob_state_y = txn[0].clone();
8876 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8877 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8878 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);
8880 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8881 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8882 // the onchain detection of the HTLC output
8883 assert_eq!(htlc_txn.len(), 2);
8884 check_spends!(htlc_txn[0], bob_state_y);
8885 check_spends!(htlc_txn[1], bob_state_y);
8890 fn test_pre_lockin_no_chan_closed_update() {
8891 // Test that if a peer closes a channel in response to a funding_created message we don't
8892 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8895 // Doing so would imply a channel monitor update before the initial channel monitor
8896 // registration, violating our API guarantees.
8898 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8899 // then opening a second channel with the same funding output as the first (which is not
8900 // rejected because the first channel does not exist in the ChannelManager) and closing it
8901 // before receiving funding_signed.
8902 let chanmon_cfgs = create_chanmon_cfgs(2);
8903 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8904 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8905 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8907 // Create an initial channel
8908 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8909 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8910 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8911 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8912 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8914 // Move the first channel through the funding flow...
8915 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8917 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8918 check_added_monitors!(nodes[0], 0);
8920 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8921 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8922 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8923 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8924 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8928 fn test_htlc_no_detection() {
8929 // This test is a mutation to underscore the detection logic bug we had
8930 // before #653. HTLC value routed is above the remaining balance, thus
8931 // inverting HTLC and `to_remote` output. HTLC will come second and
8932 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8933 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8934 // outputs order detection for correct spending children filtring.
8936 let chanmon_cfgs = create_chanmon_cfgs(2);
8937 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8938 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8939 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8941 // Create some initial channels
8942 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8944 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8945 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8946 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8947 assert_eq!(local_txn[0].input.len(), 1);
8948 assert_eq!(local_txn[0].output.len(), 3);
8949 check_spends!(local_txn[0], chan_1.3);
8951 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8952 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8953 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8954 // We deliberately connect the local tx twice as this should provoke a failure calling
8955 // this test before #653 fix.
8956 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);
8957 check_closed_broadcast!(nodes[0], true);
8958 check_added_monitors!(nodes[0], 1);
8959 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8960 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8962 let htlc_timeout = {
8963 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8964 assert_eq!(node_txn[1].input.len(), 1);
8965 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8966 check_spends!(node_txn[1], local_txn[0]);
8970 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8971 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8972 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8973 expect_payment_failed!(nodes[0], our_payment_hash, true);
8976 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8977 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8978 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8979 // Carol, Alice would be the upstream node, and Carol the downstream.)
8981 // Steps of the test:
8982 // 1) Alice sends a HTLC to Carol through Bob.
8983 // 2) Carol doesn't settle the HTLC.
8984 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8985 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8986 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8987 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8988 // 5) Carol release the preimage to Bob off-chain.
8989 // 6) Bob claims the offered output on the broadcasted commitment.
8990 let chanmon_cfgs = create_chanmon_cfgs(3);
8991 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8992 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8993 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8995 // Create some initial channels
8996 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8997 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8999 // Steps (1) and (2):
9000 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9001 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
9003 // Check that Alice's commitment transaction now contains an output for this HTLC.
9004 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9005 check_spends!(alice_txn[0], chan_ab.3);
9006 assert_eq!(alice_txn[0].output.len(), 2);
9007 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9008 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9009 assert_eq!(alice_txn.len(), 2);
9011 // Steps (3) and (4):
9012 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9013 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9014 let mut force_closing_node = 0; // Alice force-closes
9015 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
9016 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
9017 check_closed_broadcast!(nodes[force_closing_node], true);
9018 check_added_monitors!(nodes[force_closing_node], 1);
9019 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9020 if go_onchain_before_fulfill {
9021 let txn_to_broadcast = match broadcast_alice {
9022 true => alice_txn.clone(),
9023 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9025 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9026 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9027 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9028 if broadcast_alice {
9029 check_closed_broadcast!(nodes[1], true);
9030 check_added_monitors!(nodes[1], 1);
9031 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9033 assert_eq!(bob_txn.len(), 1);
9034 check_spends!(bob_txn[0], chan_ab.3);
9038 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9039 // process of removing the HTLC from their commitment transactions.
9040 assert!(nodes[2].node.claim_funds(payment_preimage));
9041 check_added_monitors!(nodes[2], 1);
9042 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9043 assert!(carol_updates.update_add_htlcs.is_empty());
9044 assert!(carol_updates.update_fail_htlcs.is_empty());
9045 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9046 assert!(carol_updates.update_fee.is_none());
9047 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9049 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9050 expect_payment_forwarded!(nodes[1], nodes[0], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
9051 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9052 if !go_onchain_before_fulfill && broadcast_alice {
9053 let events = nodes[1].node.get_and_clear_pending_msg_events();
9054 assert_eq!(events.len(), 1);
9056 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9057 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9059 _ => panic!("Unexpected event"),
9062 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9063 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9064 // Carol<->Bob's updated commitment transaction info.
9065 check_added_monitors!(nodes[1], 2);
9067 let events = nodes[1].node.get_and_clear_pending_msg_events();
9068 assert_eq!(events.len(), 2);
9069 let bob_revocation = match events[0] {
9070 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9071 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9074 _ => panic!("Unexpected event"),
9076 let bob_updates = match events[1] {
9077 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9078 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9081 _ => panic!("Unexpected event"),
9084 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9085 check_added_monitors!(nodes[2], 1);
9086 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9087 check_added_monitors!(nodes[2], 1);
9089 let events = nodes[2].node.get_and_clear_pending_msg_events();
9090 assert_eq!(events.len(), 1);
9091 let carol_revocation = match events[0] {
9092 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9093 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9096 _ => panic!("Unexpected event"),
9098 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9099 check_added_monitors!(nodes[1], 1);
9101 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9102 // here's where we put said channel's commitment tx on-chain.
9103 let mut txn_to_broadcast = alice_txn.clone();
9104 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9105 if !go_onchain_before_fulfill {
9106 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9107 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9108 // If Bob was the one to force-close, he will have already passed these checks earlier.
9109 if broadcast_alice {
9110 check_closed_broadcast!(nodes[1], true);
9111 check_added_monitors!(nodes[1], 1);
9112 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9114 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9115 if broadcast_alice {
9116 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9117 // new block being connected. The ChannelManager being notified triggers a monitor update,
9118 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9119 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9121 assert_eq!(bob_txn.len(), 3);
9122 check_spends!(bob_txn[1], chan_ab.3);
9124 assert_eq!(bob_txn.len(), 2);
9125 check_spends!(bob_txn[0], chan_ab.3);
9130 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9131 // broadcasted commitment transaction.
9133 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9134 if go_onchain_before_fulfill {
9135 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9136 assert_eq!(bob_txn.len(), 2);
9138 let script_weight = match broadcast_alice {
9139 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9140 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9142 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9143 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9144 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9145 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9146 if broadcast_alice && !go_onchain_before_fulfill {
9147 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9148 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9150 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9151 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9157 fn test_onchain_htlc_settlement_after_close() {
9158 do_test_onchain_htlc_settlement_after_close(true, true);
9159 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9160 do_test_onchain_htlc_settlement_after_close(true, false);
9161 do_test_onchain_htlc_settlement_after_close(false, false);
9165 fn test_duplicate_chan_id() {
9166 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9167 // already open we reject it and keep the old channel.
9169 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9170 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9171 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9172 // updating logic for the existing channel.
9173 let chanmon_cfgs = create_chanmon_cfgs(2);
9174 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9175 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9176 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9178 // Create an initial channel
9179 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9180 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9181 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9182 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()));
9184 // Try to create a second channel with the same temporary_channel_id as the first and check
9185 // that it is rejected.
9186 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9188 let events = nodes[1].node.get_and_clear_pending_msg_events();
9189 assert_eq!(events.len(), 1);
9191 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9192 // Technically, at this point, nodes[1] would be justified in thinking both the
9193 // first (valid) and second (invalid) channels are closed, given they both have
9194 // the same non-temporary channel_id. However, currently we do not, so we just
9195 // move forward with it.
9196 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9197 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9199 _ => panic!("Unexpected event"),
9203 // Move the first channel through the funding flow...
9204 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9206 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9207 check_added_monitors!(nodes[0], 0);
9209 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9210 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9212 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9213 assert_eq!(added_monitors.len(), 1);
9214 assert_eq!(added_monitors[0].0, funding_output);
9215 added_monitors.clear();
9217 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9219 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9220 let channel_id = funding_outpoint.to_channel_id();
9222 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9225 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9226 // Technically this is allowed by the spec, but we don't support it and there's little reason
9227 // to. Still, it shouldn't cause any other issues.
9228 open_chan_msg.temporary_channel_id = channel_id;
9229 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9231 let events = nodes[1].node.get_and_clear_pending_msg_events();
9232 assert_eq!(events.len(), 1);
9234 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9235 // Technically, at this point, nodes[1] would be justified in thinking both
9236 // channels are closed, but currently we do not, so we just move forward with it.
9237 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9238 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9240 _ => panic!("Unexpected event"),
9244 // Now try to create a second channel which has a duplicate funding output.
9245 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9246 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9247 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9248 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()));
9249 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9251 let funding_created = {
9252 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9253 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9254 let logger = test_utils::TestLogger::new();
9255 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9257 check_added_monitors!(nodes[0], 0);
9258 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9259 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9260 // still needs to be cleared here.
9261 check_added_monitors!(nodes[1], 1);
9263 // ...still, nodes[1] will reject the duplicate channel.
9265 let events = nodes[1].node.get_and_clear_pending_msg_events();
9266 assert_eq!(events.len(), 1);
9268 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9269 // Technically, at this point, nodes[1] would be justified in thinking both
9270 // channels are closed, but currently we do not, so we just move forward with it.
9271 assert_eq!(msg.channel_id, channel_id);
9272 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9274 _ => panic!("Unexpected event"),
9278 // finally, finish creating the original channel and send a payment over it to make sure
9279 // everything is functional.
9280 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9282 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9283 assert_eq!(added_monitors.len(), 1);
9284 assert_eq!(added_monitors[0].0, funding_output);
9285 added_monitors.clear();
9288 let events_4 = nodes[0].node.get_and_clear_pending_events();
9289 assert_eq!(events_4.len(), 0);
9290 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9291 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9293 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9294 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9295 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9296 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9300 fn test_error_chans_closed() {
9301 // Test that we properly handle error messages, closing appropriate channels.
9303 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9304 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9305 // we can test various edge cases around it to ensure we don't regress.
9306 let chanmon_cfgs = create_chanmon_cfgs(3);
9307 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9308 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9309 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9311 // Create some initial channels
9312 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9313 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9314 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9316 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9317 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9318 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9320 // Closing a channel from a different peer has no effect
9321 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9322 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9324 // Closing one channel doesn't impact others
9325 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9326 check_added_monitors!(nodes[0], 1);
9327 check_closed_broadcast!(nodes[0], false);
9328 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9329 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9330 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9331 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);
9332 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);
9334 // A null channel ID should close all channels
9335 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9336 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9337 check_added_monitors!(nodes[0], 2);
9338 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9339 let events = nodes[0].node.get_and_clear_pending_msg_events();
9340 assert_eq!(events.len(), 2);
9342 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9343 assert_eq!(msg.contents.flags & 2, 2);
9345 _ => panic!("Unexpected event"),
9348 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9349 assert_eq!(msg.contents.flags & 2, 2);
9351 _ => panic!("Unexpected event"),
9353 // Note that at this point users of a standard PeerHandler will end up calling
9354 // peer_disconnected with no_connection_possible set to false, duplicating the
9355 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9356 // users with their own peer handling logic. We duplicate the call here, however.
9357 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9358 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9360 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9361 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9362 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9366 fn test_invalid_funding_tx() {
9367 // Test that we properly handle invalid funding transactions sent to us from a peer.
9369 // Previously, all other major lightning implementations had failed to properly sanitize
9370 // funding transactions from their counterparties, leading to a multi-implementation critical
9371 // security vulnerability (though we always sanitized properly, we've previously had
9372 // un-released crashes in the sanitization process).
9373 let chanmon_cfgs = create_chanmon_cfgs(2);
9374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9376 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9378 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9379 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()));
9380 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()));
9382 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9383 for output in tx.output.iter_mut() {
9384 // Make the confirmed funding transaction have a bogus script_pubkey
9385 output.script_pubkey = bitcoin::Script::new();
9388 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9389 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()));
9390 check_added_monitors!(nodes[1], 1);
9392 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()));
9393 check_added_monitors!(nodes[0], 1);
9395 let events_1 = nodes[0].node.get_and_clear_pending_events();
9396 assert_eq!(events_1.len(), 0);
9398 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9399 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9400 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9402 let expected_err = "funding tx had wrong script/value or output index";
9403 confirm_transaction_at(&nodes[1], &tx, 1);
9404 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9405 check_added_monitors!(nodes[1], 1);
9406 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9407 assert_eq!(events_2.len(), 1);
9408 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9409 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9410 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9411 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9412 } else { panic!(); }
9413 } else { panic!(); }
9414 assert_eq!(nodes[1].node.list_channels().len(), 0);
9417 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9418 // In the first version of the chain::Confirm interface, after a refactor was made to not
9419 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9420 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9421 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9422 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9423 // spending transaction until height N+1 (or greater). This was due to the way
9424 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9425 // spending transaction at the height the input transaction was confirmed at, not whether we
9426 // should broadcast a spending transaction at the current height.
9427 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9428 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9429 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9430 // until we learned about an additional block.
9432 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9433 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9434 let chanmon_cfgs = create_chanmon_cfgs(3);
9435 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9436 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9437 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9438 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9440 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9441 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9442 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9443 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9444 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9446 nodes[1].node.force_close_channel(&channel_id).unwrap();
9447 check_closed_broadcast!(nodes[1], true);
9448 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9449 check_added_monitors!(nodes[1], 1);
9450 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9451 assert_eq!(node_txn.len(), 1);
9453 let conf_height = nodes[1].best_block_info().1;
9454 if !test_height_before_timelock {
9455 connect_blocks(&nodes[1], 24 * 6);
9457 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9458 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9459 if test_height_before_timelock {
9460 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9461 // generate any events or broadcast any transactions
9462 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9463 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9465 // We should broadcast an HTLC transaction spending our funding transaction first
9466 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9467 assert_eq!(spending_txn.len(), 2);
9468 assert_eq!(spending_txn[0], node_txn[0]);
9469 check_spends!(spending_txn[1], node_txn[0]);
9470 // We should also generate a SpendableOutputs event with the to_self output (as its
9472 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9473 assert_eq!(descriptor_spend_txn.len(), 1);
9475 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9476 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9477 // additional block built on top of the current chain.
9478 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9479 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9480 expect_pending_htlcs_forwardable!(nodes[1]);
9481 check_added_monitors!(nodes[1], 1);
9483 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9484 assert!(updates.update_add_htlcs.is_empty());
9485 assert!(updates.update_fulfill_htlcs.is_empty());
9486 assert_eq!(updates.update_fail_htlcs.len(), 1);
9487 assert!(updates.update_fail_malformed_htlcs.is_empty());
9488 assert!(updates.update_fee.is_none());
9489 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9490 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9491 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9496 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9497 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9498 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9502 fn test_forwardable_regen() {
9503 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9504 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9506 // We test it for both payment receipt and payment forwarding.
9508 let chanmon_cfgs = create_chanmon_cfgs(3);
9509 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9510 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9511 let persister: test_utils::TestPersister;
9512 let new_chain_monitor: test_utils::TestChainMonitor;
9513 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9514 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9515 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9516 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9518 // First send a payment to nodes[1]
9519 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9520 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9521 check_added_monitors!(nodes[0], 1);
9523 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9524 assert_eq!(events.len(), 1);
9525 let payment_event = SendEvent::from_event(events.pop().unwrap());
9526 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9527 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9529 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9531 // Next send a payment which is forwarded by nodes[1]
9532 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9533 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9534 check_added_monitors!(nodes[0], 1);
9536 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9537 assert_eq!(events.len(), 1);
9538 let payment_event = SendEvent::from_event(events.pop().unwrap());
9539 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9540 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9542 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9544 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9546 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9547 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9548 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9550 let nodes_1_serialized = nodes[1].node.encode();
9551 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9552 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9553 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9554 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9556 persister = test_utils::TestPersister::new();
9557 let keys_manager = &chanmon_cfgs[1].keys_manager;
9558 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);
9559 nodes[1].chain_monitor = &new_chain_monitor;
9561 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9562 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9563 &mut chan_0_monitor_read, keys_manager).unwrap();
9564 assert!(chan_0_monitor_read.is_empty());
9565 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9566 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9567 &mut chan_1_monitor_read, keys_manager).unwrap();
9568 assert!(chan_1_monitor_read.is_empty());
9570 let mut nodes_1_read = &nodes_1_serialized[..];
9571 let (_, nodes_1_deserialized_tmp) = {
9572 let mut channel_monitors = HashMap::new();
9573 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9574 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9575 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9576 default_config: UserConfig::default(),
9578 fee_estimator: node_cfgs[1].fee_estimator,
9579 chain_monitor: nodes[1].chain_monitor,
9580 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9581 logger: nodes[1].logger,
9585 nodes_1_deserialized = nodes_1_deserialized_tmp;
9586 assert!(nodes_1_read.is_empty());
9588 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9589 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9590 nodes[1].node = &nodes_1_deserialized;
9591 check_added_monitors!(nodes[1], 2);
9593 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9594 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9595 // the commitment state.
9596 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9598 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9600 expect_pending_htlcs_forwardable!(nodes[1]);
9601 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9602 check_added_monitors!(nodes[1], 1);
9604 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9605 assert_eq!(events.len(), 1);
9606 let payment_event = SendEvent::from_event(events.pop().unwrap());
9607 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9608 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9609 expect_pending_htlcs_forwardable!(nodes[2]);
9610 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9612 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9613 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9616 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9617 let chanmon_cfgs = create_chanmon_cfgs(2);
9618 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9619 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9620 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9622 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9624 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9625 .with_features(InvoiceFeatures::known());
9626 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9628 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9631 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9632 check_added_monitors!(nodes[0], 1);
9633 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9634 assert_eq!(events.len(), 1);
9635 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9636 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9637 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9639 expect_pending_htlcs_forwardable!(nodes[1]);
9640 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9643 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9644 check_added_monitors!(nodes[0], 1);
9645 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9646 assert_eq!(events.len(), 1);
9647 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9648 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9649 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9650 // At this point, nodes[1] would notice it has too much value for the payment. It will
9651 // assume the second is a privacy attack (no longer particularly relevant
9652 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9653 // the first HTLC delivered above.
9656 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9657 nodes[1].node.process_pending_htlc_forwards();
9659 if test_for_second_fail_panic {
9660 // Now we go fail back the first HTLC from the user end.
9661 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9663 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9664 nodes[1].node.process_pending_htlc_forwards();
9666 check_added_monitors!(nodes[1], 1);
9667 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9668 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9670 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9671 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9672 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9674 let failure_events = nodes[0].node.get_and_clear_pending_events();
9675 assert_eq!(failure_events.len(), 2);
9676 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9677 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9679 // Let the second HTLC fail and claim the first
9680 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9681 nodes[1].node.process_pending_htlc_forwards();
9683 check_added_monitors!(nodes[1], 1);
9684 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9685 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9686 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9688 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9690 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9695 fn test_dup_htlc_second_fail_panic() {
9696 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9697 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9698 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9699 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9700 do_test_dup_htlc_second_rejected(true);
9704 fn test_dup_htlc_second_rejected() {
9705 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9706 // simply reject the second HTLC but are still able to claim the first HTLC.
9707 do_test_dup_htlc_second_rejected(false);
9711 fn test_inconsistent_mpp_params() {
9712 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9713 // such HTLC and allow the second to stay.
9714 let chanmon_cfgs = create_chanmon_cfgs(4);
9715 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9716 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9717 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9719 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9720 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9721 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9722 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9724 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9725 .with_features(InvoiceFeatures::known());
9726 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9727 assert_eq!(route.paths.len(), 2);
9728 route.paths.sort_by(|path_a, _| {
9729 // Sort the path so that the path through nodes[1] comes first
9730 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9731 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9733 let payment_params_opt = Some(payment_params);
9735 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9737 let cur_height = nodes[0].best_block_info().1;
9738 let payment_id = PaymentId([42; 32]);
9740 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();
9741 check_added_monitors!(nodes[0], 1);
9743 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9744 assert_eq!(events.len(), 1);
9745 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9747 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9750 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();
9751 check_added_monitors!(nodes[0], 1);
9753 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9754 assert_eq!(events.len(), 1);
9755 let payment_event = SendEvent::from_event(events.pop().unwrap());
9757 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9758 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9760 expect_pending_htlcs_forwardable!(nodes[2]);
9761 check_added_monitors!(nodes[2], 1);
9763 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9764 assert_eq!(events.len(), 1);
9765 let payment_event = SendEvent::from_event(events.pop().unwrap());
9767 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9768 check_added_monitors!(nodes[3], 0);
9769 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9771 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9772 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9773 // post-payment_secrets) and fail back the new HTLC.
9775 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9776 nodes[3].node.process_pending_htlc_forwards();
9777 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9778 nodes[3].node.process_pending_htlc_forwards();
9780 check_added_monitors!(nodes[3], 1);
9782 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9783 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9784 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9786 expect_pending_htlcs_forwardable!(nodes[2]);
9787 check_added_monitors!(nodes[2], 1);
9789 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9790 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9791 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9793 expect_payment_failed_conditions!(nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9795 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();
9796 check_added_monitors!(nodes[0], 1);
9798 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9799 assert_eq!(events.len(), 1);
9800 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9802 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9806 fn test_keysend_payments_to_public_node() {
9807 let chanmon_cfgs = create_chanmon_cfgs(2);
9808 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9809 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9810 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9812 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9813 let network_graph = nodes[0].network_graph;
9814 let payer_pubkey = nodes[0].node.get_our_node_id();
9815 let payee_pubkey = nodes[1].node.get_our_node_id();
9816 let route_params = RouteParameters {
9817 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9818 final_value_msat: 10000,
9819 final_cltv_expiry_delta: 40,
9821 let scorer = test_utils::TestScorer::with_penalty(0);
9822 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9823 let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9825 let test_preimage = PaymentPreimage([42; 32]);
9826 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9827 check_added_monitors!(nodes[0], 1);
9828 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9829 assert_eq!(events.len(), 1);
9830 let event = events.pop().unwrap();
9831 let path = vec![&nodes[1]];
9832 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9833 claim_payment(&nodes[0], &path, test_preimage);
9837 fn test_keysend_payments_to_private_node() {
9838 let chanmon_cfgs = create_chanmon_cfgs(2);
9839 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9840 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9841 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9843 let payer_pubkey = nodes[0].node.get_our_node_id();
9844 let payee_pubkey = nodes[1].node.get_our_node_id();
9845 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9846 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9848 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9849 let route_params = RouteParameters {
9850 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9851 final_value_msat: 10000,
9852 final_cltv_expiry_delta: 40,
9854 let network_graph = nodes[0].network_graph;
9855 let first_hops = nodes[0].node.list_usable_channels();
9856 let scorer = test_utils::TestScorer::with_penalty(0);
9857 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9858 let route = find_route(
9859 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9860 nodes[0].logger, &scorer, &random_seed_bytes
9863 let test_preimage = PaymentPreimage([42; 32]);
9864 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9865 check_added_monitors!(nodes[0], 1);
9866 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9867 assert_eq!(events.len(), 1);
9868 let event = events.pop().unwrap();
9869 let path = vec![&nodes[1]];
9870 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9871 claim_payment(&nodes[0], &path, test_preimage);
9874 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9875 #[derive(Clone, Copy, PartialEq)]
9876 enum ExposureEvent {
9877 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9879 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9881 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9882 AtUpdateFeeOutbound,
9885 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9886 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9889 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9890 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9891 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9892 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9893 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9894 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9895 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9896 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9898 let chanmon_cfgs = create_chanmon_cfgs(2);
9899 let mut config = test_default_channel_config();
9900 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9901 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9902 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9903 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9905 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9906 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9907 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9908 open_channel.max_accepted_htlcs = 60;
9910 open_channel.dust_limit_satoshis = 546;
9912 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9913 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9914 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9916 let opt_anchors = false;
9918 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9921 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9922 chan.holder_dust_limit_satoshis = 546;
9926 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9927 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()));
9928 check_added_monitors!(nodes[1], 1);
9930 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()));
9931 check_added_monitors!(nodes[0], 1);
9933 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9934 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9935 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9937 let dust_buffer_feerate = {
9938 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9939 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9940 chan.get_dust_buffer_feerate(None) as u64
9942 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;
9943 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9945 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;
9946 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9948 let dust_htlc_on_counterparty_tx: u64 = 25;
9949 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9952 if dust_outbound_balance {
9953 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9954 // Outbound dust balance: 4372 sats
9955 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9956 for i in 0..dust_outbound_htlc_on_holder_tx {
9957 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9958 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9961 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9962 // Inbound dust balance: 4372 sats
9963 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9964 for _ in 0..dust_inbound_htlc_on_holder_tx {
9965 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9969 if dust_outbound_balance {
9970 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9971 // Outbound dust balance: 5000 sats
9972 for i in 0..dust_htlc_on_counterparty_tx {
9973 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9974 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9977 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9978 // Inbound dust balance: 5000 sats
9979 for _ in 0..dust_htlc_on_counterparty_tx {
9980 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9985 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9986 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9987 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 });
9988 let mut config = UserConfig::default();
9989 // With default dust exposure: 5000 sats
9991 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9992 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9993 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)));
9995 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)));
9997 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9998 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 });
9999 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10000 check_added_monitors!(nodes[1], 1);
10001 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10002 assert_eq!(events.len(), 1);
10003 let payment_event = SendEvent::from_event(events.remove(0));
10004 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10005 // With default dust exposure: 5000 sats
10007 // Outbound dust balance: 6399 sats
10008 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10009 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10010 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);
10012 // Outbound dust balance: 5200 sats
10013 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);
10015 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10016 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10017 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10019 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10020 *feerate_lock = *feerate_lock * 10;
10022 nodes[0].node.timer_tick_occurred();
10023 check_added_monitors!(nodes[0], 1);
10024 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);
10027 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10028 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10029 added_monitors.clear();
10033 fn test_max_dust_htlc_exposure() {
10034 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10035 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10036 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10037 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10038 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10039 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10040 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10041 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10042 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10043 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10044 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10045 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);